萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 多位元組安全截取中文字串函數 (支援 UTF-8/GB2312)

問題背景

substr() 按位元組截取,中文 UTF-8 (3-4 位元組) 或 GB2312 (2 位元組) 會導致亂碼。需依編碼逐字元截取。

通用函數實作

<?php
/**
 * 多位元組安全截取
 *
 * @param string $string   原字串
 * @param int    $sublen   截取字元數
 * @param int    $start    起始位置 (字元數)
 * @param string $encoding 'UTF-8' 或 'GB2312' 等
 * @return string
 */
function msubstr($string, $sublen, $start = 0, $encoding = 'UTF-8') {
    if (function_exists('mb_substr')) {
        return mb_substr($string, $start, $sublen, $encoding);
    }

    // 回退:無 mbstring 擴充時的相容實作
    if ($encoding === 'UTF-8') {
        // UTF-8 正則匹配單一字元
        $pattern = '/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf]{2}|\xf0[\x90-\xbf][\x80-\xbf]{3}|[\xf1-\xf7][\x80-\xbf]{3}/';
        preg_match_all($pattern, $string, $matches);
        $chars = $matches[0];
        $slice = array_slice($chars, $start, $sublen);
        $result = implode('', $slice);
        return (count($chars) > $start + $sublen) ? $result . '...' : $result;
    } else {
        // GB2312/Big5 等雙位元組編碼簡易處理
        $strlen = strlen($string);
        $result = '';
        for ($i = 0, $count = 0; $i < $strlen && $count < $sublen; $i++) {
            if ($i < $start) { $count++; continue; }
            $ord = ord($string[$i]);
            if ($ord > 129) { // 雙位元組字元
                $result .= substr($string, $i, 2);
                $i++;
            } else {
                $result .= $string[$i];
            }
            $count++;
        }
        return ($strlen > $start + $sublen * 2) ? $result . '...' : $result;
    }
}

// 使用範例
$str = '頂置車頂起困境檲上盯協押畏奇才趄肯困楞右腳可愛有';
echo msubstr($str, 10, 0, 'UTF-8') . '<br>';   // 頂置車頂起困境檲上盯...
echo msubstr($str, 10, 0, 'GB2312') . '<br>'; // 需確保檔案編碼為 GB2312

現代最佳實務:直接使用 mbstring

<?php
// 確保 php.ini 啟用 extension=mbstring
// 設定內部編碼
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

// 直接使用
echo mb_substr($str, 0, 10, 'UTF-8'); // 截取前 10 字
echo mb_strimwidth($str, 0, 20, '...', 'UTF-8'); // 按寬度截取 (中文算 2 寬度)

編碼偵測與轉換

<?php
$encoding = mb_detect_encoding($str, ['UTF-8', 'GB2312', 'BIG5'], true);
if ($encoding !== 'UTF-8') {
    $str = mb_convert_encoding($str, 'UTF-8', $encoding);
}
// 統一內部使用 UTF-8 處理,輸出時再按需轉碼

效能建議

  • 優先使用 mb_substr (C 底層實作,極快)。
  • 避免在迴圈中重複呼叫 mb_substr 處理長字串,改用 mb_str_split (PHP 7.4+) 一次轉陣列。
  • 資料庫層面直接用 LEFT()、SUBSTRING() (支援字元語意) 完成截取再傳給 PHP。
copyright © 萬盛學電腦網 all rights reserved