PHP 提供兩種分割字串函數:explode()(固定分隔字串)與 split()(正則分隔)。注意:split() 自 PHP 5.3 棄用,PHP 7.0 移除,新代碼請改用 preg_split()。
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array
PREG_SPLIT_NO_EMPTY 移除空元素<?php
$str = "php_strting_function.html";
$ex = explode("_", $str);
print_r($ex);
// Array([0]=>php [1]=>strting [2]=>function.html)
$pr = preg_split("/[_.]/", $str);
print_r($pr);
// Array([0]=>php [1]=>strting [2]=>function [3]=>html)
?>
| 場景 | 推薦函數 | 理由 |
|---|---|---|
| 固定字元分隔(CSV、路徑、底線) | explode() | 極快、記憶體少 |
| 多種分隔字元、複雜規則 | preg_split() | 正則彈性 |
| 分割後需保留分隔符 | preg_split(..., PREG_SPLIT_DELIM_CAPTURE) | 正則捕獲組 |
| 固定寬度切割 | str_split() / mb_str_split() | 按長度切割 |
PREG_SPLIT_NO_EMPTY:略過空結果PREG_SPLIT_OFFSET_CAPTURE:回傳位移資訊棄用 split(),善用 explode() 與 preg_split() 兼顧效能與彈性。