Home>Article>Backend Development> How to implement the Chinese character to Pinyin conversion function in PHP

How to implement the Chinese character to Pinyin conversion function in PHP

藏色散人
藏色散人 Original
2021-02-25 09:30:17 1963browse

How to implement the php Chinese character to Pinyin function: first create a PHP sample file; then create a pin class; finally define "function Pinyin($_String, $_Code='gb2312'){...} "Method to convert Chinese characters into Pinyin.

How to implement the Chinese character to Pinyin conversion function in PHP

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

The example of this article shares with you the method of converting Chinese characters into pinyin with PHP The function code is for your reference. The specific implementation content is as follows

='5.0') ? array_combine($_TDataKey, $_TDataValue) : $this->Arr_Combine($_TDataKey, $_TDataValue); arsort($_Data); reset($_Data); if($_Code != 'gb2312') $_String = $this->U2_Utf8_Gb($_String); $_Res = ''; for($i=0; $i160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; } $_Res .= $this->Pinyins($_P, $_Data); } return $_Res; //return preg_replace("/[^a-z0-9]*/", '', $_Res); } function Pinyins($_Num, $_Data){ if ($_Num>0 && $_Num<160 ) return chr($_Num); elseif($_Num<-20319 || $_Num>-10247) return ''; else { foreach($_Data as $k=>$v){ if($v<=$_Num) break; } return $k; } } function U2_Utf8_Gb($_C){ $_String = ''; if($_C < 0x80){ $_String .= $_C; }elseif($_C < 0x800){ $_String .= chr(0xC0 | $_C>>6); $_String .= chr(0x80 | $_C & 0x3F); }elseif($_C < 0x10000){ $_String .= chr(0xE0 | $_C>>12); $_String .= chr(0x80 | $_C>>6 & 0x3F); $_String .= chr(0x80 | $_C & 0x3F); }elseif($_C < 0x200000) { $_String .= chr(0xF0 | $_C>>18); $_String .= chr(0x80 | $_C>>12 & 0x3F); $_String .= chr(0x80 | $_C>>6 & 0x3F); $_String .= chr(0x80 | $_C & 0x3F); } return iconv('UTF-8', 'GB2312', $_String); } function Arr_Combine($_Arr1, $_Arr2){ for($i=0; $iPinyin(' 中 华 人 民','UTF8'); ?>

I hope this article will be helpful to everyone in learning PHP programming. [Recommended learning: "PHP Video Tutorial"]

The above is the detailed content of How to implement the Chinese character to Pinyin conversion function in PHP. For more information, please follow other related articles on the PHP Chinese website!

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