汉字转拼音

data文件:

链接:https://pan.baidu.com/s/1fLHP6Tx-36Ax9-WfhwwhUw 

提取码:eduf 

 

姓氏是有问题的。例如 “解” 姓应该是“xie” 而不是“jie”

 1 /**
 2      * 中文转拼音 (utf8版,gbk转utf8也可用)
 3      * @param string $str         utf8字符串
 4      * @param string $ret_format  返回格式 [all:全拼音|first:首字母|one:仅第一字符首字母]
 5      * @param string $placeholder 无法识别的字符占位符
 6      * @param string $allow_chars 允许的非中文字符
 7      * @return string             拼音字符串
 8      */
 9     function pinyin($str, $ret_format = 'all', $placeholder = '_', $allow_chars = '/[a-zA-Z\d ]/') {
10         static $pinyins = null;
11 
12         if (null === $pinyins) {
13             $data = file_get_contents('data.txt');
14 
15             $rows = explode('|', $data);
16 
17             $pinyins = array();
18             foreach($rows as $v) {
19                 list($py, $vals) = explode(':', $v);
20                 $chars = explode(',', $vals);
21 
22                 foreach ($chars as $char) {
23                     $pinyins[$char] = $py;
24                 }
25             }
26         }
27 
28         $str = trim($str);
29         $len = mb_strlen($str, 'UTF-8');
30         $rs = '';
31         for ($i = 0; $i < $len; $i++) {
32             $chr = mb_substr($str, $i, 1, 'UTF-8');
33             $asc = ord($chr);
34             if ($asc < 0x80) { // 0-127
35                 if (preg_match($allow_chars, $chr)) { // 用参数控制正则
36                     $rs .= $chr; // 0-9 a-z A-Z 空格
37                 } else { // 其他字符用填充符代替
38                     $rs .= $placeholder;
39                 }
40             } else { // 128-255
41                 if (isset($pinyins[$chr])) {
42                     $rs .= 'first' === $ret_format ? $pinyins[$chr][0] : ($pinyins[$chr] . ' ');
43                 } else {
44                     $rs .= $placeholder;
45                 }
46             }
47 
48             if ('one' === $ret_format && '' !== $rs) {
49                 return $rs[0];
50             }
51         }
52 
53         return rtrim($rs, ' ');
54     }

 

转载于:https://www.cnblogs.com/leee99/p/11062991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值