php汉字unicode编码与解码

WBOY
Release: 2016-07-25 08:53:44
Original
1570 people have browsed it
  1. //将内容进行unicode编码,编码后的内容格式:yoka\u738b (原始:yoka王)

  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).base_convert(ord($c2), 10, 16);
  13. }
  14. else
  15. {
  16. $str .= $c2;
  17. }
  18. }
  19. return $str;
  20. } // (脚本学堂 bbs.it-home.org 编辑整理)
  21. // 将unicode编码后的内容进行解码,编码后的内容格式:yoka\u738b (原始:yoka王)

  22. function unicode_decode($name)
  23. {
  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. }
复制代码

测试:

  1. echo '

    yoka\u738b -> '.unicode_decode('yoka\u738b').'

    ';
  2. $name = 'yoka王';
  3. echo '

    '.unicode_encode($name).'

    ';
复制代码

注意:新浪博客的编辑器把/ ** * /全都给过滤了



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!