Home > Backend Development > PHP Tutorial > PHP Chinese character unicode encoding and decoding

PHP Chinese character unicode encoding and decoding

WBOY
Release: 2016-07-25 08:53:44
Original
1734 people have browsed it
  1. //Encode the content into unicode, the encoded content format: yokau738b (original: yoka king)

  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-byte text
  13. $str .= 'u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
  14. }
  15. else
  16. {
  17. $ str .= $c2;
  18. }
  19. }
  20. return $str;
  21. } // (Edited and organized by Scripting School bbs.it-home.org)

  22. // Unicode encoded content Decode, the encoded content format: yokau738b (original: yoka king)

  23. function unicode_decode($name)
  24. {
  25. // Convert encoding, convert unicode encoding into browseable 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

Test:

  1. echo '

    yokau738b -> '.unicode_decode('yokau738b').'

    ';
  2. $name = 'yokawang';
  3. echo '

    ' .unicode_encode($name).'

    ';
Copy code

Note: The editor of Sina Blog filters all /** */



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