A search on the internet is full of "PHP to pinyin", but the code only supports GB2312,
Even the words "Taobao", "Taobao", and "Hui" cannot be supported.
The code for converting Chinese names into pinyin is far from enough.
Now I am releasing a correct GBK-to-Pinyin code. thanks to the author: Ma Minglian (! Hightman home: http://php.twomice.net
The original DEMO only supports one word query. I changed it to a string that can be used in both Chinese and English. The original text is returned in English, and the Chinese characters are converted to pinyin with tones.
At present, it does not support polyphonic words. for example, "Zeng" will be converted to ceng2 without zeng1.
(There is a yii-chinese PHP project on the network. Unfortunately, the conversion to pinyin is also GB2312)
Usage:
$ Str = 'Chinese characters abc123-= + ';
$ Py = pinyin: instance (); // single instance. if you want to, $ py = new pinyin.
Echo $ py-> get ($ str );
Download the entire code at the end of the page.
- Class pinyin {
- Var $ _ fp = false;
- Function _ construct (){
- $ _ Dat = DISCUZ_ROOT. "./source/include/table/py. dat ";
- If (! $ This-> _ fp)
- $ This-> _ fp = fopen ($ _ dat, 'RB ');
- }
- /**
- * Return a simple instance
- * @ Return
- */
- Function & instance (){
- Static $ object;
- If (empty ($ object )){
- $ Object = new self ();
- }
- Return $ object;
- }
- Function anystring2gbk ($ str ){
- $ Encode = mb_detect_encoding ($ str, "ASCII, UNICODE, UTF-8, GBK, CP936, EUC-CN, BIG-5, EUC-TW ");
- Return ($ encode! = 'Cp936' & $ encode! = 'Ascii '& $ encode! = 'Gbk '? Iconv ($ encode, 'gbk', $ str): $ str );
- }
- Function get ($ str, $ separator = ''){
- // $ Str = iconv ('utf-8', 'gbk', $ str );
- $ Str = anystring2gbk ($ str); // If you can confirm the input encoding, you can use the previous line of code.
- $ Len = strlen ($ str );
- $ I = 0; $ result = array ();
- While ($ I <$ len ){
- $ S = ord ($ str {$ I });
- If ($ s & gt; 160 ){
- $ Word = $ this-> word2py ($ s, ord ($ str {++ $ I }));
- } Else {
- $ Word = $ str {$ I };
- }
- $ Result [] = $ word;
- ++ $ I;
- }
- Return implode ($ separator, $ result );
- }
- Private function word2py ($ h, $ l ){
- $ High = $ h-0x81;
- $ Low = $ l-0x40;
- // Calculate the offset
- $ Off = ($ high <8) + $ low-($ high * 0x40 );
- // Determine the off value
- If ($ off <0 ){
- Return chr ($ h). chr ($ l );
- }
- Fseek ($ this-> _ fp, $ off * 8, SEEK_SET );
- $ Ret = fread ($ this-> _ fp, 8 );
- $ Ret = unpack ('a8py', $ ret );
- Return $ ret ['py'];
- }
- Function _ destruct (){
- If ($ this-> _ fp)
- Fclose ($ this-> _ fp );
- }
- }
- ?>
|