此文章来源于后羿之弓,转载请注明出处

转载内容,主要是为了解决经过js的escape后的如’%u5B9D%u9A6C’内容还原成utf-8。有兴趣的可以看一下。

方法一:

  1. /**
  2. * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
  3. * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
  4. *
  5. * @param string $source escaped with Javascript's escape() function
  6. * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
  7. * @return string
  8. */
  9. function unescape($source, $iconv_to = 'UTF-8') {
  10. $decodedStr = '';
  11. $pos = 0;
  12. $len = strlen ($source);
  13. while ($pos < $len) {
  14. $charAt = substr ($source, $pos, 1);
  15. if ($charAt == '%') {
  16. $pos++;
  17. $charAt = substr ($source, $pos, 1);
  18. if ($charAt == 'u') {
  19. // we got a unicode character
  20. $pos++;
  21. $unicodeHexVal = substr ($source, $pos, 4);
  22. $unicode = hexdec ($unicodeHexVal);
  23. $decodedStr .= code2utf($unicode);
  24. $pos += 4;
  25. }
  26. else {
  27. // we have an escaped ascii character
  28. $hexVal = substr ($source, $pos, 2);
  29. $decodedStr .= chr (hexdec ($hexVal));
  30. $pos += 2;
  31. }
  32. }
  33. else {
  34. $decodedStr .= $charAt;
  35. $pos++;
  36. }
  37. }
  38. <br/>if ($iconv_to != 'UTF-8') {
  39. $decodedStr = iconv('UTF-8', $iconv_to, $decodedStr);
  40. }
  41. <br/>return $decodedStr;
  42. }
  43. /**
  44. * Function coverts number of utf char into that character.
  45. * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
  46. *
  47. * @param int $num
  48. * @return utf8char
  49. */
  50. function code2utf($num)
  51. {
  52.    if($num<128)return chr($num);
  53.    if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
  54.    if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  55.    if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
  56.    return '';
  57. }
  58. exit;

方法二(来自神仙居)

avascript有个escape函数,虽然现在已经不建议使用,但还是会碰到许多escape过的字符串需要解码。因为javascript的escape实际上是个unicode编码,要转成utf8或者其他编码是很麻烦的。php5.2内置的json扩展除了用于json以外,其实也可以用来unescape。

json / javascript里的字符串在字符串常量的表示里,也可以用\u5C71这样的方式,而escape的结果里,只是把那个 \ 换成了 % 。所以,只要用类似下面的代码就可以转换回来。而对于\u5C71这种形式的编码的串,只需要在两头加上双引号,然后json_decode就可以了。

  1. echo json_decode(str_replace('%','\\', "%u5B9D%u9A6C"));