在 PHP 中截取包含中文的字串時,直接使用 substr() 會按位元組切割,導致中文字元被截斷產生亂碼。雖然 mb_substr() 是標準解法,但理解其底層原理有助於處理特殊場景(如無 mbstring 擴展的環境)。本文深度解析 UTF-8 編碼規則,實作純 PHP 版無損截取函數。
UTF-8 使用 1-4 個位元組編碼單一字元,透過位元組首位標記識別:
| 位元組數 | 首位元組模式 | 碼點範圍 | 範例 |
|---|---|---|---|
| 1 | 0xxxxxxx | U+0000 ~ U+007F | ASCII 英數字元 |
| 2 | 110xxxxx | U+0080 ~ U+07FF | 希臘文、西里爾文 |
| 3 | 1110xxxx | U+0800 ~ U+FFFF | 中日韓統一表意文字(含中文) |
| 4 | 11110xxx | U+10000 ~ U+10FFFF | Emoji、罕用漢字 |
<?php
/**
* 不依賴 mbstring 的 UTF-8 安全截取函數
* @param string $str 待截取字串
* @param int $length 截取字元數(非位元組數)
* @return string 截取結果
*/
function utf8_sub(string $str, int $length): string
{
if ($length <= 0) return '';
$result = '';
$offset = 0;
$charCount = 0;
$byteLength = strlen($str);
while ($charCount < $length && $offset < $byteLength) {
$firstByte = ord($str[$offset]);
// 判斷字元佔用位元組數
if ($firstByte < 0x80) { // 0xxxxxxx (1 byte)
$charBytes = 1;
} elseif (($firstByte & 0xE0) === 0xC0) { // 110xxxxx (2 bytes)
$charBytes = 2;
} elseif (($firstByte & 0xF0) === 0xE0) { // 1110xxxx (3 bytes)
$charBytes = 3;
} elseif (($firstByte & 0xF8) === 0xF0) { // 11110xxx (4 bytes)
$charBytes = 4;
} else {
// 非法序列,跳過單一位元組避免死循環
$charBytes = 1;
}
// 邊界檢查:避免讀取超出字串長度
if ($offset + $charBytes > $byteLength) {
break;
}
$result .= substr($str, $offset, $charBytes);
$offset += $charBytes;
$charCount++;
}
return $result;
}
// 測試
$testStr = '中華ah人民hdj';
echo "原始: {$testStr}\n";
echo "截取前5字元: " . utf8_sub($testStr, 5) . "\n"; // 輸出: 中華ah人
echo "mb_substr 對照: " . mb_substr($testStr, 0, 5, 'UTF-8') . "\n"; // 相同結果
?>
function utf8_substr(string $str, int $start, ?int $length = null): string
{
if ($start < 0) {
// 負數起始位置:從結尾往前計算
$totalChars = utf8_strlen($str);
$start = max(0, $totalChars + $start);
}
$result = '';
$offset = 0;
$charIndex = 0;
$byteLength = strlen($str);
while ($offset < $byteLength) {
$firstByte = ord($str[$offset]);
$charBytes = ($firstByte < 0x80) ? 1 :
(($firstByte & 0xE0) === 0xC0) ? 2 :
(($firstByte & 0xF0) === 0xE0) ? 3 :
(($firstByte & 0xF8) === 0xF0) ? 4 : 1;
if ($charIndex >= $start) {
if ($length !== null && $charIndex >= $start + $length) break;
$result .= substr($str, $offset, $charBytes);
}
$offset += $charBytes;
$charIndex++;
}
return $result;
}
function utf8_strlen(string $str): int
{
$count = 0;
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$byte = ord($str[$i]);
if ($byte < 0x80 || ($byte & 0xC0) !== 0x80) {
$count++; // 計算非延續位元組
}
}
return $count;
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
mb_substr() | 原生支援、效能最佳、功能完整 | 需安裝 mbstring 擴展 | 現代 PHP 專案首選 |
grapheme_substr() | 支援書寫字素群(如 Emoji 組合) | 需 intl 擴展、PHP 7.3+ | 複雜 Unicode 處理 |
| 純 PHP 實作 | 零依賴、可移植 | 效能較低、需自行處理邊界情況 | 受限環境、教學用途 |
理解 UTF-8 位元組結構是處理多語言字串的基礎。生產環境請優先使用 mb_substr() 或 grapheme_substr();本文提供的純 PHP 實作適用於無擴展環境或作為學習參考,核心邏輯為解析首位元組判斷字元長度,再按字元而非位元組截取。