基於預編碼拼音表(pytable_without_tune.txt),提供靜態方法獲取首字母、全拼、可選大小寫,支援混合中英數字串。
getChineseFirstChar($str, $firstOnly=false, $upper=false):取首字母或首字全拼getChineseChar($str, $firstOnly=false, $upper=false):整串轉拼音,空格分隔utf8_str_split() 正確切分 UTF-8 字元<?php
class Helper_Spell {
static public function getArray() {
return unserialize(file_get_contents('pytable_without_tune.txt'));
}
static public function getChineseFirstChar($string, $isOne=false, $upper=false) {
$spell = self::getArray();
$chars = self::utf8_str_split($string, 1);
$first = $chars[0];
if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $first)) {
$result = $spell[$first][0];
} else {
$result = $first;
}
$result = $isOne ? substr($result, 0, 1) : $result;
return $upper ? strtoupper($result) : $result;
}
static public function getChineseChar($string, $isOne=false, $upper=false) {
$spell = self::getArray();
$chars = self::utf8_str_split($string, 1);
$result = [];
foreach ($chars as $char) {
if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $char)) {
$py = $spell[$char][0];
} else {
$py = $char;
}
$py = $isOne ? substr($py, 0, 1) : $py;
$result[] = $upper ? strtoupper($py) : $py;
}
return implode(' ', $result);
}
private static function utf8_str_split($str, $len=1) {
if (!ctype_digit((string)$len) || $len < 1) return false;
$mbLen = mb_strlen($str, 'UTF-8');
if ($mbLen <= $len) return [$str];
preg_match_all('/.{'.$len.'}|[^\x00]{1,'.$len.'}$/us', $str, $m);
return $m[0];
}
}
?>
echo Helper_Spell::getChineseFirstChar('我是作者'); // wo
echo Helper_Spell::getChineseFirstChar('我是作者', true); // w
echo Helper_Spell::getChineseFirstChar('我是作者', true, true); // W
echo Helper_Spell::getChineseChar('我是作者'); // wo shi zuo zhe
echo Helper_Spell::getChineseChar('我是作者', true); // w s z z
echo Helper_Spell::getChineseChar('我是作者', false, true); // WO SHI ZUO ZHE
pytable_without_tune.txt 為序列化陣列,鍵為漢字,值為拼音陣列(如 '我' => ['wo', 'wo3'])。可從開源專案(如 overtrue/pinyin)匯出或自行編碼。
$spellArray 避免重複讀檔