Home  >  Article  >  Backend Development  >  php unicode解码工具(unicode编码转换器)

php unicode解码工具(unicode编码转换器)

WBOY
WBOYOriginal
2016-07-25 08:55:161475browse
  1. //Unicode编码解码转换
  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 {
  8. $c = $name[$i];
  9. $c2 = $name[$i + 1];
  10. if (ord($c) > 0)
  11. { //两个字节的文字
  12. $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
  13. }
  14. else
  15. {
  16. $str .= $c2;
  17. }
  18. }
  19. return $str;
  20. }
  21. //将UNICODE编码后的内容进行解码
  22. function unicode_decode($name)
  23. { // bbs.it-home.org
  24. //转换编码,将Unicode编码转换成可以浏览的utf-8编码
  25. $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
  26. preg_match_all($pattern, $name, $matches);
  27. if (!empty($matches))
  28. {
  29. $name = '';
  30. for ($j = 0; $j {
  31. $str = $matches[0][$j];
  32. if (strpos($str, '\\u') === 0)
  33. {
  34. $code = base_convert(substr($str, 2, 2), 16, 10);
  35. $code2 = base_convert(substr($str, 4), 16, 10);
  36. $c = chr($code).chr($code2);
  37. $c = iconv('UCS-2', 'UTF-8', $c);
  38. $name .= $c;
  39. }
  40. else
  41. {
  42. $name .= $str;
  43. }
  44. }
  45. }
  46. return $name;
  47. }
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn