本文使用「署名 4.0 国际 (CC BY 4.0)」许可协议,欢迎转载、或重新修改使用,但需要注明来源。 [署名 4.0 国际 (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/deed.zh) 本文作者: 苏洋 创建时间: 2012年02月10日 统计字数: 2606字 阅读时间: 6分钟阅读 本文链接: https://soulteary.com/2012/02/10/php%E6%A8%A1%E6%8B%9Fjavascript%E7%9A%84escape%E4%BB%A5%E5%8F%8Aunescape.html ----- # PHP 模拟 JavaScript 的 escape 以及 unescape 这个类相当好用.作用么,PHP做JSON传递GBK字符,比如中文,日文,韩文神马的Unicode最合适不过了.. ```php 1) { // 多字节字符 $return .= '%u' . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding))); } else { $return .= '%' . strtoupper(bin2hex($str)); } } return $return; } function gb2utf8($string, $encoding = 'utf-8', $from_encode = 'gb2312') { return mb_convert_encoding($string, $encoding, $from_encode); } } ?> ``` google code 上找到的另外一个类似脚本 ```php =127) { $tmpString=bin2hex(iconv("gbk", "ucs-2", substr($str,$i,2))); $tmpString=substr($tmpString,2,2).substr($tmpString,0,2); $retrunString.="%u".$tmpString; $i++; } else { $retrunString.="%".dechex(ord($str[$i])); } } return $retrunString; } 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("UTF-8","UCS-2",$v)); } return join("",$ar); } function phpunescape ($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; } function unescape($str) { $str = rawurldecode($str); preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U", $str, $r); $ar = $r[0]; #print_r($ar); 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) == "&#") { //echo substr($v,2,-1).""; $ar[$k] = iconv("UCS-2", "UTF-8", pack("n",substr($v,2,-1))); } } return join("",$ar); } ?> ```