py_class 是一個純 PHP 實現的漢字轉拼音工具類,特點包括:
完整類別定義如下,核心為 $pinyin 靜態映射陣列,將區位碼映射至拼音聲母韻母組合。
<?php
class py_class {
function py_class() {
$this->pinyin = array(
"a" => array(59371, 41648, 50400, 33157, 41392, 18661, 47599),
"ai" => array(19697, 32178, 35504, 36856, 20712, 25068, 28663, 26608, 29399, 19381, 17099, 47497, 30339, 43240, 54250, 56459, 45201, 25005, 57749, 17131, 36057, 28596, 49375, 29162, 55685, 31713, 27114, 64665, 19190, 56536, 37508, 22145, 59104, 42373, 18930, 17311, 30185, 29599, 54922, 60552, 35971, 19670, 27069, 47505, 56476, 52365, 63875, 43184, 17031, 45460, 45466, 43440, 32176, 44464, 57310, 36230, 41904, 42672, 42928, 42416, 42160, 18330, 22758, 52719, 58012, 27797, 45716, 44208, 44720, 23788, 45302, 25559, 49645, 30387, 51430, 56208, 24969, 51680, 44976, 16588, 46209, 43696, 43952, 18334, 57994, 29916, 51424, 34439),
/* ... 此處省略極長的映射陣列,實際使用請複製完整原始碼 ... */
"zuo" => array(61932, 53739, 33225, 18050, 25788, 31432, 63191, 35536, 63959, 63703, 27065, 38882, 39606, 32182, 62167, 62423, 62679, 62860, 59610, 63447, 38591, 63116)
);
}
function str2py($s) {
$s = preg_replace("/\s/is", "_", $s);
$s = preg_replace("/(\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\+|\=|\{|\}|\[|\]|\||\\|\:|\;|\"|\'|\<|\,|\>|\.|\?|\/)/is", "", $s);
$py = "";
// 自動識別 UTF-8:若「拼音」二字節數大於 4,判定為 UTF-8 並轉 GBK
if (strlen("拼音") > 4) $s = iconv('utf-8', 'gbk', $s);
for ($i = 0; $i < strlen($s); $i++) {
if (ord($s[$i]) > 128) {
// 取雙字節區位碼
$py .= $this->asi2py(ord($s[$i]) + ord($s[$i + 1]) * 256);
$i++;
} else {
$py .= $s[$i];
}
if (strlen($py) >= 20) return $py; // 限制長度
}
return $py;
}
function asi2py($a) {
$py = $this->pinyin;
foreach ($py as $k => $v) {
if (in_array($a, $v)) return $k;
}
return '';
}
}
?>
require_once 'py_class.php';
$py = new py_class();
// 輸出:huhehaoteshi
echo $py->str2py("呼和浩特市");
strlen("拼音") > 4 判斷當前腳本編碼,若為 UTF-8 環境會自動 iconv 轉為 GBK 以匹配內部映射表(映射表基於 GBK 區位碼)。str2py 預設最長返回 20 字元,可根據需求調整或移除該限制。