php制作unicode解码工具(unicode编码转换器)代码分享

php制作Unicode编码解码在线转换工具代码分享。

  1. <?php
  2. function unicode_encode($name)
  3. {
  4. $name = iconv('UTF-8', 'UCS-2', $name);
  5. $len = strlen($name);
  6. $str = '';
  7. for ($i = 0; $i < $len - 1; $i = $i + 2)
  8. {
  9. $c = $name[$i];
  10. $c2 = $name[$i + 1];
  11. if (ord($c) > 0)
  12. { //两个字节的文字
  13. $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
  14. }
  15. else
  16. {
  17. $str .= $c2;
  18. }
  19. }
  20. return $str;
  21. }
  22. //将UNICODE编码后的内容进行解码
  23. function unicode_decode($name)
  24. {
  25. //转换编码,将Unicode编码转换成可以浏览的utf-8编码
  26. $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
  27. preg_match_all($pattern, $name, $matches);
  28. if (!emptyempty($matches))
  29. {
  30. $name = '';
  31. for ($j = 0; $j < count($matches[0]); $j++)
  32. {
  33. $str = $matches[0][$j];
  34. if (strpos($str, '\\u') === 0)
  35. {
  36. $code = base_convert(substr($str, 2, 2), 16, 10);
  37. $code2 = base_convert(substr($str, 4), 16, 10);
  38. $c = chr($code).chr($code2);
  39. $c = iconv('UCS-2', 'UTF-8', $c);
  40. $name .= $c;
  41. } //phpfensi.com
  42. else
  43. {
  44. $name .= $str;
  45. }
  46. }
  47. }
  48. return $name;
  49. }