PHP GBK 转 拼音pinyin,注意不是网络上到处都是的GB2312转拼音
绝非是网络上一搜,到处都有的「PHP转拼音」,那种代码只支持GB2312,连「骞」、「鹜」、「慧」等字都无法支持。对于姓名转拼音,那个代码远远不够使用。现在 公布正确的GBK转拼音代码,很感谢原作者: 马明练(!hightman) 主页: http://php.twomice.net原DEMO只支持一个字查询,我 修改了成支持一段字符串,中英文均可,英文返回原文,汉字转化为拼音,并带音调。暂不支持多音字,例如「曾」会转化为ceng2,而没有zeng1 (网络上有一个yii-chinese项目,转拼音也是GB2312)使用方法:$str = '汉字中文abc123-=+';$py = pinyin::instance(); //我习惯单实例,如果你愿意,$py = new pinyin(); 也可以。echo $py->get($str);请在页尾下载整个代码。
snap0000153.png
imgs/asCode/26151236_9yD7.png
[PHP]代码
<?php
class pinyin{
var $_fp = false;
function __construct() {
$_dat = DISCUZ_ROOT."./source/include/table/py.dat";
if (!$this->_fp)
$this->_fp = fopen($_dat,'rb');
}
/**
* return a simple instance
* @return
*/
function &instance() {
static $object;
if(empty($object)) {
$object = new self();
}
return $object;
}
function anystring2gbk($str) {
$encode = mb_detect_encoding($str,"ASCII,UNICODE,UTF-8,GBK,CP936,EUC-CN,BIG-5,EUC-TW");
return ($encode != 'CP936' && $encode != 'ASCII' && $encode != 'GBK' ? iconv($encode,'GBK',$str) : $str);
}
function get($str,$separator = ' ') {
//$str = iconv('UTF-8','GBK',$str);
$str = anystring2gbk($str); //如果您可以确定输入编码,可以使用上一行代码
$len = strlen($str);
$i = 0;$result = array();
while ($i < $len) {
$s = ord($str{$i});
if ($s > 160) {
$word = $this->word2py($s,ord($str{++$i}));
} else {
$word = $str{$i};
}
$result[] = $word;
++$i;
}
return implode($separator,$result);
}
private function word2py($h,$l) {
$high = $h - 0x81;
$low = $l - 0x40;
// 计算偏移位置
$off = ($high<<8) + $low - ($high * 0x40);
// 判断 off 值
if ($off < 0) {
return chr($h).chr($l);
}
fseek($this->_fp, $off * 8, SEEK_SET);
$ret = fread($this->_fp, 8);
$ret = unpack('a8py', $ret);
return $ret['py'];
}
function __destruct() {
if ($this->_fp)
fclose($this->_fp);
}
}
?>






