分类:
2008-05-29 10:22:18
让PHP解码JAVASCRIPT的escape编码可以使用以下两个方法,一个是编码,一个是解码,要想正确运行以下两个函数需要为PHP添加配置iconv模块 php程序员站
添加配置iconv模块
function escape($str) {
preg_match_all("/[\x80-\xff].|[\x01-\x7f]+/",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(ord($v[0]) < 128)
$ar[$k] = rawurlencode($v);
else
//$ar[$k] = "%u".bin2hex(iconv("GB2312","UCS-2",$v));
$ar[$k] = "%u".bin2hex(iconv("GBK","UCS-2",$v));//这里更正
}
return join("",$ar);
}
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/%u.|.;|\d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4)));
elseif(substr($v,0,3) == "")
$ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1)));
elseif(substr($v,0,2) == "") {
$ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}