汉字转拼音 繁体字 加音标的
今天分享一个可以将汉字转为拼音的 而且也可以加音标的类,
这个要感谢,那些巨人的肩膀啊
代码如下:
<?php
define('BASE_PATH', dirname(__FILE__));
class Tpinyin {
protected $dict = array();
protected $dictfile = 'pylib.gif';
protected $dictoffs = 244;
protected $tune = array();
private $charset = '';
private $maxlength = 0;
private $fp;
function __construct() {
$this->dictfile = BASE_PATH . '/'. $this->dictfile;
$fp = fopen($this->dictfile, 'rb');
fread($fp, 41);
$this->dict[] = explode(',', fread($fp, 57));
$this->dict[] = explode(',', fread($fp, 146));
}
function settune() {
$tune = array(
'a' => array("\x01\x01","\x00\xe1","\x01\xce","\x00\xe0",),
'e' => array("\x01\x13","\x00\xe9","\x01\x1b","\x00\xe8",),
'i' => array("\x01\x2b","\x00\xed","\x01\xd0","\x00\xec",),
'o' => array("\x01\x4d","\x00\xf3","\x01\xd2","\x00\xf2",),
'u' => array("\x01\x6b","\x00\xfa","\x01\xd4","\x00\xf9",),
'v' => array("\x01\xd6","\x01\xd8","\x01\xda","\x01\xdc",),
);
foreach($tune as $k=>$r)
foreach($r as $i=>$v)
$this->tune[$k][$i] = mb_convert_encoding($v, $this->charset, 'UCS-2');
}
function pinyin($str) {
$this->charset = mb_check_encoding($str, 'UTF-8') ? 'UTF-8' : 'GBK';
// $this->settune();//是否加音标
$this->fp = fopen($this->dictfile, 'rb');
$this->maxlength = filesize($this->dictfile);
$str = mb_convert_encoding($str, "UCS-2", "UTF-8, GBK");
$t = array_map(array($this, 'pinyin_back'), str_split($str, 2));
return join('', $t); //连接成串,要不要自己决定
}
function pinyin_back($ch) {
if(ord($ch{0}) == 0) return $ch{1};
$o = hexdec(bin2hex($ch)) - 0x4e00;
if($o < 0 || $o >= $this->maxlength) return mb_convert_encoding($ch, $this->charset, 'UCS-2');
fseek($this->fp, $o*2 + $this->dictoffs);
$x = sprintf('%05d', current(unpack('S', fread($this->fp, 2))));
$t = $this->dict[0][substr($x, 0, 2)+0] . $this->dict[1][substr($x, 2, 2)+0];
$n = substr($x, -1) - 1;
$s = $t;
foreach($this->tune as $k=>$v) {
$s = str_replace($k, $v[$n], $s);
if($s != $t) break;
}
return "$s";//加了个空格,要不要自己决定
}
}
这个文件是需要一个库的,但是那位大神将库放在了图片里面,我觉得很牛叉,于是就这样用了,呵呵
使用方式如下
$p = new Tpinyin;
echo $p->pinyin('惘');
结果自己试试就知道了。
如果想控制音标的话,可以考虑是不是加载这个函数settune,有加的话,就会有音标的。
版权声明
由 davidzhang创作并维护的 Gowhich博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证。
本文首发于 博客( https://www.gowhich.com ),版权所有,侵权必究。
本文永久链接: https://www.gowhich.com/blog/291
版权声明
由 davidzhang创作并维护的 Gowhich博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证。
本文首发于 Gowhich博客( https://www.gowhich.com ),版权所有,侵权必究。
本文永久链接: https://www.gowhich.com/blog/291