Google搜索

浏览存档

« 七月 2008  
周日 周一 周二 周三 周四 周五 周六
    1 2 3 4 5
6 8 9 10 11 12
13 14 15 16 18
20 21 22 23 24 25 26
27 28 29 30 31    

用户登录

最新评论

在线用户

当前共有 0 users 和 2 guests 在线。

订阅到RSS阅读器

Syndicate content

类似javascript的unescape方法的php实现

Written by dfar2008  in   2006 十月 01 , 星期日 13:32

一般情况下,当通过ajax把输入的值传给php时都要进行escape,php通过request获得传过来的值,保存的数据库中。这样的存取方法对英文等单字节语言是没有任何问题,但是对于双字节的中文简体,繁体,韩文和日文等就会出现问题,保存后显示为乱码。

经分析,php保存之前应该先对request传过来的值进行unescape,进行解码,这样才能正常保存中文等双字节。

因此要找一个与javascript的unescape类似的php方法,有人介绍urldocode和rawurldecode方法,但试了试都不行,最后找到一个和我遇到同样的问题的朋友的blog,他找到了一个解决方法,试了试,搞定。
他的blog:http://pure-essence.net/archives/2005/03/29/javascript-unescape-php-function/

具体方法在下面:
<?
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;
}
?>

Last Updated (2006 十月 01 , 星期日 13:42)