js的escape转义中文php的转换函数

很多时候需要用到js的escape函数来转换中文字符,可是用js转换后的字符怎么用php来转换回来呢,下面我就找到了两个很实用的函数。

GB2312编码:

  1. function unescape($str) {
  2. $str = rawurldecode($str);
  3. preg_match_all("/%u.{4}|&#x.{4};|&#d+;|.+/U",$str,$r);
  4. $ar = $r[0];
  5. foreach($ar as $k=>$v) {
  6. if(substr($v,0,2) == "%u")
  7. $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4)));
  8. elseif(substr($v,0,3) == "&#x")
  9. $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1)));
  10. elseif(substr($v,0,2) == "&#") {
  11. $ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1)));
  12. }
  13. }
  14. return join("",$ar);
  15. }

UTF8编码:

  1. function unescape($str){
  2. $ret = '';
  3. $len = strlen($str);
  4. for ($i = 0; $i < $len; $i++){
  5. if ($str[$i] == '%' && $str[$i+1] == 'u'){
  6. $val = hexdec(substr($str, $i+2, 4));
  7. if ($val < 0x7f) $ret .= chr($val);
  8. else if($val < 0x800) $ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
  9. else $ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
  10. $i += 5;
  11. }
  12. else if ($str[$i] == '%'){
  13. $ret .= urldecode(substr($str, $i, 3));
  14. $i += 2;
  15. }
  16. else $ret .= $str[$i];
  17. }
  18. return $ret;
  19. }