pinyin.inc.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. //decode by http://dezend.qiling.org QQ 2859470
  3. function utf82gb($utfstr)
  4. {
  5. if (function_exists('iconv')) {
  6. return iconv('utf-8', 'gbk', $utfstr);
  7. }
  8. global $UC2GBTABLE;
  9. $okstr = '';
  10. if (trim($utfstr) == '') {
  11. return $utfstr;
  12. }
  13. if (empty($UC2GBTABLE)) {
  14. $filename = MYMPS_DATA . '/gb2312-utf8.table';
  15. $fp = fopen($filename, 'r');
  16. while ($l = fgets($fp, 15)) {
  17. $UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6));
  18. }
  19. fclose($fp);
  20. }
  21. $okstr = '';
  22. $ulen = strlen($utfstr);
  23. for ($i = 0; $i < $ulen; $i++) {
  24. $c = $utfstr[$i];
  25. $cb = decbin(ord($utfstr[$i]));
  26. if (strlen($cb) == 8) {
  27. $csize = strpos(decbin(ord($cb)), '0');
  28. for ($j = 0; $j < $csize; $j++) {
  29. $i++;
  30. $c .= $utfstr[$i];
  31. }
  32. $c = utf82u($c);
  33. if (isset($UC2GBTABLE[$c])) {
  34. $c = dechex($UC2GBTABLE[$c] + 32896);
  35. $okstr .= chr(hexdec($c[0] . $c[1])) . chr(hexdec($c[2] . $c[3]));
  36. } else {
  37. $okstr .= '&#' . $c . ';';
  38. }
  39. } else {
  40. $okstr .= $c;
  41. }
  42. }
  43. $okstr = trim($okstr);
  44. return $okstr;
  45. }
  46. function GetPinyin($str, $ishead = 0, $isclose = 1)
  47. {
  48. global $pinyins;
  49. global $db;
  50. global $db_mymps;
  51. global $charset;
  52. $restr = '';
  53. $str = $charset == 'utf-8' ? utf82gb(trim($str)) : trim($str);
  54. $slen = strlen($str);
  55. if ($slen < 2) {
  56. return $str;
  57. }
  58. if (count($pinyins) == 0) {
  59. $fp = fopen(MYMPS_DATA . '/pinyin.db', 'r');
  60. while (!feof($fp)) {
  61. $line = trim(fgets($fp));
  62. $pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
  63. }
  64. fclose($fp);
  65. }
  66. for ($i = 0; $i < $slen; $i++) {
  67. if (128 < ord($str[$i])) {
  68. $c = $str[$i] . $str[$i + 1];
  69. $i++;
  70. if (isset($pinyins[$c])) {
  71. if ($ishead == 0) {
  72. $restr .= $pinyins[$c];
  73. } else {
  74. $restr .= $pinyins[$c][0];
  75. }
  76. } else {
  77. $restr .= '-';
  78. }
  79. } else {
  80. if (@eregi('[a-z0-9]', $str[$i])) {
  81. $restr .= $str[$i];
  82. } else {
  83. $restr .= '_';
  84. }
  85. }
  86. }
  87. if ($isclose == 0) {
  88. unset($pinyins);
  89. }
  90. return strtolower($restr);
  91. }