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