在 PHP 開發中,漢字與區位碼的相互轉換是一個經常遇到的需求,尤其在處理舊系統遷移、印刷排版或特定編碼環境時顯得尤為重要。本文將詳細解析一個完整的 PHP 實例,實現漢字轉區位碼與區位碼轉漢字的雙向轉換功能,並附帶簡易的 Web 介面供測試使用。
區位碼是中國國家標準 GB2312 編碼中對漢字的編碼方式,每個漢字佔用兩個字節,高字節為「區號」,低字節為「位號」,均以 160 (0xA0) 為偏移量。PHP 中可利用 ord() 取得字節 ASCII 值,配合 chr() 還原字符,即可完成轉換。
if ($t1 != "") {
$t2 = sprintf("%02d%02d", ord($t1[0]) - 160, ord($t1[1]) - 160);
}
此處 $t1 為輸入的單個漢字(GB2312 編碼雙字節),透過減去 160 偏移後,以兩位數字格式輸出區號與位號,例如「中」字區位碼為 5448。
if ($t3 != "") {
$t4 = chr(substr($t3, 0, 2) + 160) . chr(substr($t3, 2, 2) + 160);
}
將四位數字的區位碼拆分為區號與位號,各加 160 後透過 chr() 還原為雙字節漢字。
以下程式碼包含表單介面與轉換邏輯,儲存為 gb2312_zone.php 即可直接執行(需確保檔案編碼為 GB2312):
<?php
$t1 = $_POST['textfield1'] ?? '';
$t2 = $_POST['textfield2'] ?? '';
$t3 = $_POST['textfield3'] ?? '';
$t4 = $_POST['textfield4'] ?? '';
// 漢字 → 區位碼
if ($t1 !== '') {
$t2 = sprintf("%02d%02d", ord($t1[0]) - 160, ord($t1[1]) - 160);
}
// 區位碼 → 漢字
if ($t3 !== '') {
$t4 = chr((int)substr($t3, 0, 2) + 160) . chr((int)substr($t3, 2, 2) + 160);
}
?>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>漢字區位碼雙向查詢系統</title>
<style>
body { font-family: 'Microsoft JhengHei', sans-serif; background: #f4f6f8; }
.container { max-width: 600px; margin: 40px auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
h2 { text-align: center; color: #2c3e50; margin-bottom: 24px; }
.form-group { display: flex; gap: 10px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }
label { font-weight: 500; color: #34495e; }
input[type="text"] { flex: 1; min-width: 180px; padding: 10px 12px; border: 1px solid #dfe6e9; border-radius: 4px; font-size: 15px; }
input[type="submit"] { padding: 10px 24px; background: #3498db; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 15px; transition: background .2s; }
input[type="submit"]:hover { background: #2980b9; }
hr { border: none; border-top: 1px solid #eee; margin: 24px 0; }
</style>
</head>
<body>
<div class="container">
<h2>漢字區位碼雙向查詢系統</h2>
<form method="post">
<div class="form-group">
<label>輸入漢字</label>
<input type="text" name="textfield1" value="<?= htmlspecialchars($t1) ?>" placeholder="例如:中" />
<input type="submit" name="submit1" value="轉換為區位碼" />
<label>區位碼結果</label>
<input type="text" name="textfield2" value="<?= htmlspecialchars($t2) ?>" readonly />
</div>
</form>
<hr />
<form method="post">
<div class="form-group">
<label>輸入區位碼</label>
<input type="text" name="textfield3" value="<?= htmlspecialchars($t3) ?>" placeholder="例如:5448" />
<input type="submit" name="submit2" value="轉換為漢字" />
<label>漢字結果</label>
<input type="text" name="textfield4" value="<?= htmlspecialchars($t4) ?>" readonly />
</div>
</form>
</div>
</body>
</html>
mb_convert_encoding 處理。透過 PHP 內建的 ord()、chr() 與字串操作函式,我們能輕鬆實現漢字與區位碼的雙向轉換。掌握此原理不僅有助於維護舊系統,也能在編碼轉換、字符檢索等場景中發揮作用。完整程式碼已整理優化,可直接部署使用或整合至既有專案中。