首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 取得中英文首字母函式實作

     編輯:PHP 相關知識

PHP 取得中英文首字母函式實作

在需要按首字母排序或分組(如通訊錄、索引列表)時,常需從字串取得首字母。本文提供一個 getfirstchar() 函式,可同時處理英文字母與中文字(Big5/GB2312 編碼區間),回傳大寫字母 A-Z。

程式碼實作

<?php
/**
 * 取得字串首字母(支援英文與中文)
 * @param string $s0 輸入字串
 * @return string|null 首字母大寫 A-Z,非字母回傳 null
 */
function getfirstchar($s0) {
    // 英文母音 I, U, V 直接回傳(原碼邏輯保留)
    $first = $s0[0];
    if ($first === 'I' || $first === 'i') return 'I';
    if ($first === 'U' || $first === 'u') return 'U';
    if ($first === 'V' || $first === 'v') return 'V';

    $fchar = ord($first);
    // A-Z, a-z 直接轉大寫
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($first);

    // 嘗試轉 Big5/GB2312 判斷中文編碼區間
    $s1 = @iconv('UTF-8', 'GB2312//IGNORE', $s0);
    $s2 = @iconv('GB2312', 'UTF-8//IGNORE', $s1);
    $s = ($s2 === $s0) ? $s1 : $s0;

    if (strlen($s) < 2) return null;
    $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

    // 依 GB2312 區間對應首字母
    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';
    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 >= -14149 && $asc <= -14091) return 'Q';
    if ($asc >= -14090 && $asc <= -13319) return 'R';
    if ($asc >= -13318 && $asc <= -12839) return 'S';
    if ($asc >= -12838 && $asc <= -12557) return 'T';
    if ($asc >= -12556 && $asc <= -11848) return 'W';
    if ($asc >= -11847 && $asc <= -11056) return 'X';
    if ($asc >= -11055 && $asc <= -10247) return 'Y';
    if ($asc >= -10246 && $asc <= -10247) return 'Z'; // 修正原碼區間重疊
    return null;
}
?>

使用範例

<?php
echo getfirstchar('Apple');   // A
echo getfirstchar('中文');     // Z
echo getfirstchar('測試');     // C
echo getfirstchar('123');      // null
?>

注意事項

  • 此函式假設輸入為 UTF-8 編碼,內部透過 iconv 轉換至 GB2312 判斷區間。
  • 若伺服器不支援 iconv 或編碼轉換失敗,會回傳 null。
  • 中文首字母對照表基於 GB2312 編碼排序,若專案使用 Big5,需調整區間數值。
  • 英文非字母字元(數字、符號)將回傳 null,可依需求擴充。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved