PHP汉字转拼音的两种步骤+PHP提取汉字(中文)方法
程序员文章站
2022-06-08 08:45:27
...
PHP汉字转拼音的两种方法+PHP提取汉字(中文)方法
方法一:根据ASCII码转换,GB2312库对多音字也无能为力。
方法二:根据拼音组合数组检索
PHP取得汉字(中文):
方法一:根据ASCII码转换,GB2312库对多音字也无能为力。
GB2312标准共收录6763个汉字,不在范围内的汉字是无法转换,如:中国前总理*的“镕”字。
GB2312中对所收汉字进行了“分区”处理,每区含有94个汉字/符号。这种表示方式也称为区位码。
01-09区为特殊符号。
16-55区为一级汉字,按拼音排序。(3755个)
56-87区为二级汉字,按部首/笔画排序。(3008个)
10-15区及88-94区则未有编码。
占用的码位是72*94=6768。其中有5个空位是D7FA-D7FE。所以实际共6763个汉字。其中一级汉字3755个,二级汉字3008个。而此类算法实际只能转换3755个汉字。
优点:没有使用大文字库,文件相对较小,没有使用正则表达式,性能相对较高。支持首字母转换。
缺点:没有在GB2312中收录的汉字无法转换,多音字无法识别。
(如果对拼音转换要求不高的朋友,建议使用这个。)
0x80) { $ascii2 = ord($s{++$i}); $ascii = $ascii * 256 + $ascii2 - 65536; } if($ascii 0) { if(($ascii >= 48 && $ascii = 97 && $ascii = 65 && $ascii -10247) { $res .= '_'; }else{ foreach($pinyin_arr as $py=>$asc) { if($asc 0xE0) { $s = self::utf8_to_gb2312($s{0}.$s{1}.$s{2}); }elseif($ascii = 65 && $ascii = 97 && $ascii =-20319 && $asc=-20283 && $asc=-19775 && $asc=-19218 && $asc=-18710 && $asc=-18526 && $asc=-18239 && $asc=-17922 && $asc=-17417 && $asc=-16474 && $asc=-16212 && $asc=-15640 && $asc=-15165 && $asc=-14922 && $asc=-14914 && $asc=-14630 && $asc=-14149 && $asc=-14090 && $asc=-13318 && $asc=-12838 && $asc=-12556 && $asc=-11847 && $asc=-11055 && $asc
方法二:根据拼音组合数组检索
set_char($str,$charset,"gb2312"); $str=$this->c($str); $str=$this->set_char($str,"gb2312",$charset); }else{ $str=$this->c($str); } return $str; } private function set_char($str,$charset="utf-8",$charset_out="gb2312"){ if(function_exists('iconv')){ $str=iconv($charset,$charset_out,$str); }elseif(function_exists("mb_convert_encoding")){ $str=mb_convert_encoding($str,$charset_out,$charset); } return $str; } private function g($num){ if($num>0 && $num-10247){ return ""; }else{ for($i=count($this->d)-1;$i>=0;$i--){ if($this->d[$i][1]d[$i][0]; } } private function c($str){ $ret=""; for($i=0;$i160){ $q=ord(substr($str,++$i,1)); $p=$p*256+$q-65536; } $ret.=$this->g($p); } return $ret; }}function get_pinyin($str,$charset="utf-8"){ $pinyin=new pinyin(); return $pinyin->get_pinyin($str,$charset);}?>
PHP取得汉字(中文):
function getChinese($str,$charset='utf8'){ if($charset=='gb2312'){ if(!preg_match_all("/^[".chr(0xa1)."-".chr(0xff)."]+/",$str,$match)){ return false; } return implode('',$match[0]); } // if($charset=='utf8'){ if(!preg_match_all("/[\x{4e00}-\x{9fa5}]+/u",$str,$match)){ return false; } return implode('',$match[0]); } return false;}PHP取得汉字拼音字母数组标点:
//取得字符串中汉字字符数字下划线和短连接符、逗号、句号、分号、冒号、书名号、问号等非特殊字符 function getChinese($str,$charset='utf8'){ if($charset=='gb2312'){ if(!preg_match_all("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_\-\,\。\,\.\;\;\:\:\《\》\?\?\%\%\!\!\~\~]+/",$str,$match)){ return false; } return implode('',$match[0]); } if($charset=='utf8'){ if(!preg_match_all("/[\x{4e00}-\x{9fa5}A-Za-z0-9_\-\,\。\,\.\;\;\:\:\《\》\?\?\%\%\!\!\~\~]+/u",$str,$match)){ return false; } return implode('',$match[0]); } return false; }
相关文章
相关视频