在無法安裝 opencc 等系統級工具的環境下,可使用純 PHP 陣列映射表實現 UTF-8 繁簡轉換。本文提供一個 utf8_chinese 類別,內建簡體→繁體、繁體→簡體雙向映射表,無外部依賴。
<?php
class utf8_chinese {
private $utf8_gb2312; // 簡體字串
private $utf8_big5; // 繁體字串
public function __construct($data) {
$this->utf8_gb2312 = $data['sim'];
$this->utf8_big5 = $data['tra'];
}
// 簡體 → 繁體
public function gb2312_big5($str) {
return $this->_convert($str, $this->utf8_gb2312, $this->utf8_big5);
}
// 繁體 → 簡體
public function big5_gb2312($str) {
return $this->_convert($str, $this->utf8_big5, $this->utf8_gb2312);
}
private function _convert($str, $fromTable, $toTable) {
$result = '';
$len = strlen($str);
$i = 0;
while ($i < $len) {
$ord = ord($str[$i]);
// UTF-8 中文字元為 3 bytes (224-239 開頭)
if ($ord >= 224 && $ord <= 239 && $i + 2 < $len) {
$char = substr($str, $i, 3);
$pos = strpos($fromTable, $char);
if ($pos !== false) {
$result .= substr($toTable, $pos, 3);
$i += 3;
continue;
}
}
$result .= $str[$i];
$i++;
}
return $result;
}
}
?>
$UTF8_TRA = [
'sim' => '萬與丑專業叢東絲丟兩嚴喪個...', // 簡體字串(連續 3-byte 字元)
'tra' => '萬與醜專業叢東絲丟兩嚴喪個...', // 繁體字串(一一對應)
];
<?php
require 'utf8_chinese.php';
$UTF8_TRA = [ /* 完整映射表 */ ];
$chinese = new utf8_chinese($UTF8_TRA);
$simplified = '简体中文测试';
$traditional = $chinese->gb2312_big5($simplified);
echo "繁體:$traditional\n"; // 輸出:繁體中文測試
$back = $chinese->big5_gb2312($traditional);
echo "簡體:$back\n"; // 輸出:简体中文测试
?>
function cns($str) {
global $UTF8_TRA;
static $obj = null;
if ($obj === null) $obj = new utf8_chinese($UTF8_TRA);
return $obj->gb2312_big5($str);
}
// 直接使用
echo cns('简体转繁体');
| 優點 | 缺點 |
|---|---|
| 純 PHP,無擴展依賴 | 映射表體積大(約 1.5 萬常用字) |
| 部署簡單,相容性高 | 僅支援單字映射,無法處理詞彙級差異(如「軟體/軟件」) |
| 效能尚可(線性掃描) | 非標準字、生僻字可能缺表 |
opencc PHP 擴展**,支援詞彙級轉換、異體字、台灣/香港用語差異,準確度遠高於字映射表。