GBK 转 拼音pinyin,注意不是网络上到处都是的GB2312转拼音

WBOY
Freigeben: 2016-07-25 09:07:58
Original
1392 Leute haben es durchsucht
网络上一搜,到处都是的「PHP转拼音」,但是代码只支持GB2312,
连「骞」、「鹜」、「慧」等字都无法支持。
对于中文姓名转拼音,那个代码远远不够使用。

现在公布一个正确的GBK转拼音代码,很感谢原作者: 马明练(!hightman) 主页: http://php.twomice.net
原DEMO只支持一个字查询,我修改了成支持一段字符串,中英文均可,英文返回原文,汉字转化为拼音,并带音调。
暂不支持多音字,例如「曾」会转化为ceng2,而没有zeng1

(网络上有一个yii-chinese的PHP项目,可惜转拼音也是GB2312)


使用方法:
$str = '汉字中文abc123-=+';
$py = pinyin::instance(); //单实例,如果你愿意,$py = new pinyin(); 也可以。
echo $py->get($str);


请在页尾下载整个代码。


GBK 转 拼音pinyin,注意不是网络上到处都是的GB2312转拼音
  1. class pinyin{
  2. var $_fp = false;
  3. function __construct() {
  4. $_dat = DISCUZ_ROOT."./source/include/table/py.dat";
  5. if (!$this->_fp)
  6. $this->_fp = fopen($_dat,'rb');
  7. }
  8. /**
  9. * return a simple instance
  10. * @return
  11. */
  12. function &instance() {
  13. static $object;
  14. if(empty($object)) {
  15. $object = new self();
  16. }
  17. return $object;
  18. }
  19. function anystring2gbk($str) {
  20. $encode = mb_detect_encoding($str,"ASCII,UNICODE,UTF-8,GBK,CP936,EUC-CN,BIG-5,EUC-TW");
  21. return ($encode != 'CP936' && $encode != 'ASCII' && $encode != 'GBK' ? iconv($encode,'GBK',$str) : $str);
  22. }
  23. function get($str,$separator = ' ') {
  24. //$str = iconv('UTF-8','GBK',$str);
  25. $str = anystring2gbk($str); //如果您可以确定输入编码,可以使用上一行代码
  26. $len = strlen($str);
  27. $i = 0;$result = array();
  28. while ($i $s = ord($str{$i});
  29. if ($s > 160) {
  30. $word = $this->word2py($s,ord($str{++$i}));
  31. } else {
  32. $word = $str{$i};
  33. }
  34. $result[] = $word;
  35. ++$i;
  36. }
  37. return implode($separator,$result);
  38. }
  39. private function word2py($h,$l) {
  40. $high = $h - 0x81;
  41. $low = $l - 0x40;
  42. // 计算偏移位置
  43. $off = ($high
  44. // 判断 off 值
  45. if ($off return chr($h).chr($l);
  46. }
  47. fseek($this->_fp, $off * 8, SEEK_SET);
  48. $ret = fread($this->_fp, 8);
  49. $ret = unpack('a8py', $ret);
  50. return $ret['py'];
  51. }
  52. function __destruct() {
  53. if ($this->_fp)
  54. fclose($this->_fp);
  55. }
  56. }
  57. ?>
复制代码


Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!