汉字转拼音

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     }

 

posted on 2019-06-21 10:10  年华消逝青春  阅读(385)  评论(0编辑  收藏  举报

导航