php汉字转拼音

php汉字转拼音

php函数(由dedecms(dedecms/include/inc/inc_fun_funAdmin.php)的SpGetPinyin函数修改,dedecms的字典不太完全):

<?php

    function pinyin($str, $ishead) {
        static $pinyins = array();
    
        $restr = ‘‘;
        $str = trim($str);
        $slen = strlen($str);
        if($slen < 2) {
            return $str;
        }

        if(count($pinyins) == 0) {
            $fp = fopen(‘pinyin.dic‘, ‘r‘);
            while(!feof($fp)) {
                $line = trim(fgets($fp));
                $a2 = explode(‘`‘, $line);
                isset($a2[1]) && $pinyins[$a2[0]] = $a2[1];
            }
            fclose($fp);
        }
        
        for($i=0; $i<$slen; $i++) {
            if(ord($str[$i])>0x80) {
                $c = $str[$i].$str[$i+1];
                $i++;
                if(isset($pinyins[$c])) {
                    $restr.= ($ishead==0)?$pinyins[$c]:$pinyins[$c][0];
                }else {
                    $restr .= "_";
                }
            }else if( preg_match("/[a-z0-9]/i", $str[$i]) ) {
                $restr .= $str[$i];
            }
            else {
                $restr .= "_";
            }
        }

        return $restr;
    }
    
    //测试
    echo pinyin(‘舒熱佳隔热膜‘,1),‘<br>‘; 
    echo pinyin(‘舒熱佳隔热膜‘,0),‘<br>‘; 
    echo pinyin(‘鹦鹉‘,1),‘<br>‘;  
    echo pinyin(‘鹦鹉‘,0),‘<br>‘;  
    echo pinyin(‘眠之堡/依诺维绅/myside床垫‘,1),‘<br>‘; 
    echo pinyin(‘眠之堡/依诺维绅/myside床垫‘,0),‘<br>‘;  
    
    /*结果:
    srjgrm
    shurejiageremo
    yw
    yingwu
    mzb_ynws_mysidecd
    mianzhibao_yinuoweishen_mysidechuangdian*/
?>

包含的字典见附件:pinyin.rar/pinyin.dic (gbk)

下载地址:http://files.cnblogs.com/luoyunshu/pinyin.rar

参考:

http://www.oschina.net/code/snippet_862384_25415

php汉字转拼音,布布扣,bubuko.com

php汉字转拼音

上一篇:C# testJsonAsXMLNodeAttribute - XML& json & Collections - XmlNode, XmlElement, XmlAttribute,Dictionary,List


下一篇:【SQLServer】DBHelper即C#数据库底层封装