Home  >  Article  >  Backend Development  >  php unicode decoding tool (unicode encoding converter)

php unicode decoding tool (unicode encoding converter)

WBOY
WBOYOriginal
2016-07-25 08:55:161576browse
  1. //Unicode encoding and decoding conversion
  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. { //Two bytes of text
  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. //Decode the UNICODE encoded content
  23. function unicode_decode($name)
  24. { // bbs.it-home.org
  25. //Convert encoding, convert Unicode encoding into browsable utf -8 encoding
  26. $pattern = '/([w]+)|(\u([w]{4}))/i';
  27. preg_match_all($pattern, $name, $matches);
  28. if (!empty ($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. }
  42. else
  43. {
  44. $name .= $str;
  45. }
  46. }
  47. }
  48. return $name;
  49. }
Copy code


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