Home >Backend Development >PHP Tutorial >Convert Chinese characters to Pinyin (dede) in php

Convert Chinese characters to Pinyin (dede) in php

WBOY
WBOYOriginal
2016-07-25 08:47:361185browse
Convert Chinese characters to Pinyin (dede) in php
Pull an external link!
http://www.tao11.cn/a0b923820dcc509a.html
http://www.tao11.cn/9d4c2f636f067f89.html
http://www.tao11.cn/4b5ce2fe28308fd9.html
http://www.tao11 .cn/bbce2345d7772b06.html
The pinyin.dat inside is nearby
  1. /**
  2. * Chinese characters
  3. * @param string $str String to be converted
  4. * @param string $charset String encoding
  5. * @param bool $ishead Whether to extract only the first letter
  6. * @return string Return result
  7. */
  8. static function GetPinyin($str,$charset="utf-8",$ishead = 0) {
  9. $restr = '';
  10. $str = trim($str );
  11. if($charset=="utf-8"){
  12. $str=iconv("utf-8","gb2312",$str);
  13. }
  14. $slen = strlen($str);
  15. $ pinyins=array();
  16. if ($slen < 2) {
  17. return $str;
  18. }
  19. $fp = fopen(dirname(__FILE__).'/pinyin.dat', 'r');
  20. while (! feof($fp)) {
  21. $line = trim(fgets($fp));
  22. $pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
  23. }
  24. fclose($fp);
  25. for ($i = 0; $i < $slen; $i++) {
  26. if (ord($str[$i]) > 0x80) {
  27. $c = $str[$i] . $str[$i + 1];
  28. $i++;
  29. if (isset($pinyins[$c])) {
  30. if ($ishead == 0) {
  31. $restr .= $pinyins[$c];
  32. } else {
  33. $restr .= $pinyins[$c][0];
  34. }
  35. } else {
  36. $restr .= "_";
  37. }
  38. } else if ( preg_match("/[a-z0-9]/i", $str[$i])) {
  39. $restr .= $str[$i];
  40. } else {
  41. $restr .= "_";
  42. }
  43. }
  44. return $restr;
  45. }
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