欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-13 13:36:24
...
  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. }
复制代码