站长论坛

标题: 不使用iconv实现javascript中的unescape函数 [打印本页]

作者: tzlink    时间: 2007-10-6 10:26
标题: 不使用iconv实现javascript中的unescape函数
在使用AJAX的时候,在URL中使用中文传递经常会出现编码错误的。今天本来用以前那个unescape()来进行解码,后来发现服务器居然没有打开iconv扩展,超级汗,不得不找了一个类似的函数,主要从utf-8转化成gb2312。
共享之。


<?
function utf8RawUrlDecode ($source) {
    $decodedStr = "";
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $entity = "&#". $unicode . ';';
                $decodedStr .= utf8_encode ($entity);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        } else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }
    return $decodedStr;
}
?>




欢迎光临 站长论坛 (http://www.tzlink.com/bbs/) Powered by Discuz! X3.2