在建立索引、分類目錄、通訊錄排序時,常需將標題轉為首字母(A-Z)。本文提供支援中文(GB2312 區位碼對應拼音首字母)、英文、數字的完整函數實作。
function getFirstChar($str) {
// 1. 判斷首字元類型
$firstChar = $str[0] ?? '';
$ord = ord($firstChar);
// 數字 0-9
if ($ord >= 48 && $ord <= 57) return $firstChar;
// 大寫英文 A-Z
if ($ord >= 65 && $ord <= 90) return $firstChar;
// 小寫英文 a-z
if ($ord >= 97 && $ord <= 122) return strtoupper($firstChar);
// 2. 中文:轉 GB2312 計算區位碼對應拼音首字母
$gb = iconv("UTF-8", "GB2312//IGNORE", $str);
if (strlen($gb) < 2) return '#'; // 非中文或轉換失敗
$asc = ord($gb[0]) * 256 + ord($gb[1]) - 65536;
// 區位碼對應表(常用漢字範圍 -20319 ~ -10247)
if ($asc >= -20319 && $asc <= -20284) return 'A';
if ($asc >= -20283 && $asc <= -19776) return 'B';
if ($asc >= -19775 && $asc <= -19219) return 'C';
if ($asc >= -19218 && $asc <= -18711) return 'D';
if ($asc >= -18710 && $asc <= -18527) return 'E';
if ($asc >= -18526 && $asc <= -18240) return 'F';
if ($asc >= -18239 && $asc <= -17923) return 'G';
if ($asc >= -17922 && $asc <= -17418) return 'H';
if ($asc >= -17417 && $asc <= -16475) return 'J'; // 無 I
if ($asc >= -16474 && $asc <= -16213) return 'K';
if ($asc >= -16212 && $asc <= -15641) return 'L';
if ($asc >= -15640 && $asc <= -15166) return 'M';
if ($asc >= -15165 && $asc <= -14923) return 'N';
if ($asc >= -14922 && $asc <= -14915) return 'O';
if ($asc >= -14914 && $asc <= -14631) return 'P';
if ($asc >= -14630 && $asc <= -14150) return 'Q';
if ($asc >= -14149 && $asc <= -14091) return 'R';
if ($asc >= -14090 && $asc <= -13319) return 'S';
if ($asc >= -13318 && $asc <= -12839) return 'T';
if ($asc >= -12838 && $asc <= -12557) return 'W'; // 無 U,V
if ($asc >= -12556 && $asc <= -11848) return 'X';
if ($asc >= -11847 && $asc <= -11056) return 'Y';
if ($asc >= -11055 && $asc <= -10247) return 'Z';
return '#'; // 非漢字或超出範圍
}
<?php
$pdo = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8", "user", "pass");
$stmt = $pdo->query("SELECT title FROM articles");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$title = $row['title'];
$letter = getFirstChar($title);
echo "{$title} → {$letter}\n";
}
?>
#。overtrue/pinyin (Composer 套件) 或 pinyin PECL 擴展,支援 UTF-8 直轉拼音、多音字、語調、首字母,準確度高得多。composer require overtrue/pinyin,用法 Pinyin::initials($str)。