爱程序网

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*/?>

Tags:PHP