PHP 提供多種字串分割函式,適用於不同場景。本文系統整理 `str_split()` (固定長度)、`explode()` (分隔符)、`substr()` + `strlen()` (位置長度截取) 的語法、差異與選用指南。
| 函式 | 用途 | 參數 | 回傳 | 範例 |
|---|---|---|---|---|
str_split | 固定長度切割 | (string $str, int $length = 1) | 陣列 | str_split('1234', 2) → ['12','34'] |
explode | 分隔符分割 | (string $separator, string $str, int $limit = PHP_INT_MAX) | 陣列 | explode(' ', '1 2 3 4') → ['1','2','3','4'] |
substr | 位置長度截取 | (string $str, int $offset, ?int $length) | 字串 | substr('abcdef', 1, 3) → 'bcd' |
mb_substr | 多位元組安全截取 | (string $str, int $offset, ?int $length, string $encoding) | 字串 | mb_substr('中文測試', 0, 2, 'UTF-8') → '中文' |
preg_split | 正則分割 | (string $pattern, string $str, int $limit, int $flags) | 陣列 | preg_split('/\s+/', 'a b c') → ['a','b','c'] |
<?php
$str = '1234';
print_r(str_split($str)); // ['1','2','3','4'] (預設長度 1)
print_r(str_split($str, 2)); // ['12','34']
print_r(str_split($str, 3)); // ['123','4']
<?php
$str = '1 2 3 4';
print_r(explode(' ', $str)); // ['1','2','3','4']
$csv = 'a,b,c';
print_r(explode(',', $csv)); // ['a','b','c']
// 限制分割筆數
print_r(explode(',', 'a,b,c,d', 2)); // ['a', 'b,c,d']
<?php
$content = $row['game_detail'];
$len = strlen($content); // 位元組長度
if ($len > 102) {
echo substr($content, 0, 102) . '...';
} else {
echo $content;
}
// ⚠ 中文環境請用 mb_strlen / mb_substr 避免截半字元
<?php
$str = 'PHP中文截取測試';
$maxChars = 10;
if (mb_strlen($str, 'UTF-8') > $maxChars) {
echo mb_substr($str, 0, $maxChars, 'UTF-8') . '...';
} else {
echo $str;
}
str_split() (ASCII) / mb_str_split() (PHP 7.4+, 多位元組)explode() (最快)preg_split()mb_substr() + mb_strlen() (字元數) 或視覺寬度截取explode() 為 C 級實作,極快,大量資料首選。preg_split() 啟動正則引擎,較慢,僅在必要時使用。mb_* 函式有多位元組檢查開銷,純 ASCII 場景優先用非 mb 版本。字串分割核心在於**明確分割依據**:固定長度、分隔符、正則模式、字元數/位元組數截取。依據場景選用對應函式,並注意多位元組字串必須使用 `mb_*` 系列函式,才能獲得正確且高效的結果。