本類別採用查表法實現繁簡體中文編碼轉換,需搭配兩個對照表檔案(big5.map、gb.map)。雖然現代專案多改用 mb_convert_encoding() 或 opencc,但此實作展示了編碼轉換的核心邏輯。
<?php
class CCharset {
var $gb_map = "gb.map";
var $big5_map = "big5.map";
var $dep_char = 127; // 判斷雙位元組字元的閾值
// Big5 → GB2312 單字轉換
function cbig5_gb($str, $fd) {
$c = ord(substr($str, 0, 1));
$x = ord(substr($str, 1, 1));
$address = (($c - 160) * 510) + ($x - 1) * 2;
fseek($fd, $address);
return fgetc($fd) . fgetc($fd);
}
// GB2312 → Big5 單字轉換
function cgb_big5($str, $fd) {
$c = ord(substr($str, 0, 1));
$x = ord(substr($str, 1, 1));
$address = (($c - 160) * 510) + ($x - 1) * 2;
fseek($fd, $address);
return fgetc($fd) . fgetc($fd);
}
// 字串級 Big5 → GB
function Big5_Gb($str) {
$fd = fopen($this->gb_map, "r");
$str = str_replace("charset=big5", "charset=gb2312", $str);
$outstr = "";
for ($i = 0; $i < strlen($str); $i++) {
$ch = ord(substr($str, $i, 1));
if ($ch > $this->dep_char) {
$outstr .= $this->cbig5_gb(substr($str, $i, 2), $fd);
$i++;
} else {
$outstr .= substr($str, $i, 1);
}
}
fclose($fd);
return $outstr;
}
// 字串級 GB → Big5
function Gb_Big5($str) {
$fd = fopen($this->big5_map, "r");
$str = str_replace("charset=gb2312", "charset=big5", $str);
$outstr = "";
for ($i = 0; $i < strlen($str); $i++) {
$ch = ord(substr($str, $i, 1));
if ($ch > $this->dep_char) {
$outstr .= $this->cgb_big5(substr($str, $i, 2), $fd);
$i++;
} else {
$outstr .= substr($str, $i, 1);
}
}
fclose($fd);
return $outstr;
}
}
?>
<?php
include("CCharset.php3");
$obj = new CCharset;
$big5 = "這是一個Big5的文字串";
$gb = $obj->Big5_Gb($big5);
echo $gb; // 輸出 GB2312 編碼
$big5_again = $obj->Gb_Big5($gb);
echo $big5_again; // 還原為 Big5
?>
<?php
include("CCharset.php3");
$url = $QUERY_STRING; // 目標網址
$content = join('', file($url));
$content = str_replace("<head>", "<head><base href=$url>", $content); // 修正相對路徑
$converter = new CCharset;
$gbContent = $converter->Big5_Gb($content);
echo $gbContent;
?>
| 方案 | 優點 | 缺點 |
|---|---|---|
mb_convert_encoding() | 內建函式、支援多種編碼、無需外部檔案 | 繁簡轉換僅限編碼層面,無法處理詞彙差異(如「軟體」vs「软件」) |
| OpenCC (Open Chinese Convert) | 開源、支援詞彙級轉換、台灣/香港/大陸用語區分、高效能 | 需安裝擴展或呼叫外部程式 |
overtrue/pinyin + 字典 | 純 PHP、可客製化詞庫 | 效能較低、需維護詞庫 |
<?php
// 使用 overtrue/opencc (Composer 套件)
require 'vendor/autoload.php';
use OpenCC\OpenCC;
$opencc = new OpenCC('s2twp.json'); // 簡體→繁體(台灣慣用語+異體字)
$traditional = $opencc->convertSimplifiedToTraditional($simplifiedText);
// 或使用 PHP 擴展 php-opencc (效能最佳)
$od = opencc_open('s2twp.json');
$traditional = opencc_convert($od, $simplifiedText);
opencc_close($od);
?>
opencc-js) 轉換顯示