pinyin_data) { $rows = explode('|', $this->pinyin_source); $this->pinyin_data = array(); foreach($rows as $v) { list($py, $vals) = explode(':', $v); $chars = explode(',', $vals); foreach ($chars as $char) { $this->pinyin_data[$char] = $py; } } } } //获取全部拼音 public function getAllPY($str){ $format = 'all'; return $this->pinyin($str,$format); } //获取拼音首字母 public function getFirstPY($str,$is_upper = 1){ $format = 'first'; $str = $this->pinyin($str,$format); if( $is_upper ) $str = strtoupper($str); return $str; } //获取第一个字符的字母 public function getOnePY($str,$is_upper = 1){ $format = 'one'; $str = $this->pinyin($str,$format); if( $is_upper ) $str = strtoupper($str); return $str; } private function pinyin($str, $ret_format = 'all', $placeholder = '_', $allow_chars = '/[a-zA-Z\d ]/') { $str = trim($str); $len = mb_strlen($str, 'UTF-8'); $rs = ''; for ($i = 0; $i < $len; $i++) { $chr = mb_substr($str, $i, 1, 'UTF-8'); $asc = ord($chr); if ($asc < 0x80) { // 0-127 if (preg_match($allow_chars, $chr)) { // 用参数控制正则 $rs .= $chr; // 0-9 a-z A-Z 空格 } else { // 其他字符用填充符代替 $rs .= $placeholder; } } else { // 128-255 if (isset($this->pinyin_data[$chr])) { $rs .= 'first' === $ret_format ? $this->pinyin_data[$chr][0] : ($this->pinyin_data[$chr] . ' '); } else { $rs .= $placeholder; } } if ('one' === $ret_format && '' !== $rs) { return $rs[0]; } } return rtrim($rs, ' '); } }