trying to unescape with z function
echo unescape("%u65E0%u5FE7%u811A%u672C%u811A%u672C%u6280%u672F%u8BA8%u8BBA%u7248escape%u7F16%u7801%u540E%u5982%u4F55%u7528php%u8FDB%u884C%u89E3%u7801%3F");
function unescape($str)
{
$str = rawurldecode($str);
preg_match_all("/%u.{4}|&#x.{4};|&#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) == "&#x")
$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);
}
两个版本的.
<?php
function escape($str){
$res = @unpack("H*",iconv("utf-8","UCS-2",$str));
$res = preg_replace("/(.{4})/is","%u\\1",$res[1]);
return $res;
}
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,-4)));
elseif(substr($v,0,3) == "&#x")
$ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
elseif(substr($v,0,2) == "&#") {
$ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}
function escape1($str){
$sublen=strlen($str);
$reString="";
for ($i=0;$i<$sublen;$i++){
if(ord($str[$i])>=127){
$tmpString=bin2hex(iconv("GBK","ucs-2",substr($str,$i,2))); //此处GBK为目标代码的编码格式,请实际情况修改
if (!eregi("WIN",PHP_OS)){
$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);
}
$reString.="%u".$tmpString;
$i++;
} else {
$reString.="%".dechex(ord($str[$i]));
}
}
return $reString;
}
function unescape1($str) {
$str = rawurldecode($str);
preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u")
$ar[$k] =!eregi("WIN",PHP_OS)?iconv("UCS-2","GBK",strrev(pack("H4",substr($v,-4)))):iconv("UCS-2","gb2312",pack("H4",substr($v,-4)));
elseif(substr($v,0,3) == "&#x")
$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);
}
?>
我是用下面这个,只支持 utf-8 ,不需要 iconv 模块支持!个人感觉蛮好用的!
<?php
function js_unescape( $str ){
$ret = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i++){
if ($str[$i] == '%' && $str[$i+1] == 'u'){
$val = hexdec(substr($str, $i+2, 4));
if ($val < 0x7f) $ret .= chr($val);
else if($val < 0x800) $ret .= chr(0xc0 |($val>>6)).chr(0x80 |($val&0x3f));
else $ret .= chr(0xe0 |($val>>12)).chr(0x80 |(($val>>6)&0x3f)).chr(0x80 |($val&0x3f));
$i += 5;
}else if ($str[$i] == '%'){
$ret .= urldecode(substr($str, $i, 3));
$i += 2;
}else
$ret .= $str[$i];
}
return $ret;
}?>