正則表達式功能強大但**效能較差、可讀性低**。PHP 內建大量字串函數能以**原生速度**完成分割、搜尋、取代、統計等常見任務。本文精選 10 大函數,附真實場景範例與效能建議,助你寫出更快、更維護的代碼。
連續呼叫、內部維持指標,適合解析固定分隔符的結構化字串(如 CSV、日誌)。
$info = "lv chen yang|Hello:world&757104454@qq.com";
$tokens = "|:& ";
$token = strtok($info, $tokens);
while ($token !== false) {
echo "Element: $token<br>";
$token = strtok($tokens); // 後續呼叫只傳 tokens
}
**比 preg_split、split 快數倍**,首選分割工具。
$summary = "In the latest installment...";
$words = explode(' ', strip_tags($summary));
echo "單字數:" . count($words);
explode 逆操作,高效組合 SQL IN 列表、CSV 匯出等。
$cities = ["Chengdu","Chongqing","Beijing","Shanghai","Guangzhou"];
echo implode('|', $cities); // Chengdu|Chongqing|Beijing|Shanghai|Guangzhou
區分大小寫用 strpos,不區分用 stripos。**嚴格比較 === false** 判斷失敗。
$log = "192.168.1.1:/www/htdocs/index.html:[2013/06/26:13:25:10]\n...";
$pos = strpos($log, "index.html");
$end = strpos($log, "\n", $pos);
$timestamp = substr($log, $pos+strlen("index.html")+1, $end-$pos-strlen("index.html")-1);
常用於**截取摘要至最近單字結尾**,避免硬切單字。
$limit = 100;
$summary = "長文章內容...";
if (strlen($summary) > $limit) {
$summary = substr($summary, 0, strrpos(substr($summary, 0, $limit), ' ')) . '...';
}
**比 preg_replace 快得多**,適用關鍵字過濾、模板變數替換、Email 反爬蟲。
$email = "lvchenyang@live.cn";
echo str_replace('@', ' (at) ', $email); // lvchenyang (at) live.cn
搭配 ltrim() 可快速取得 Email 域名、URL 路徑等。
$url = "user@example.com";
echo ltrim(strstr($url, '@'), '@'); // example.com
支援負數位移(從末尾算起),極靈活。
$str = "lvchenyang";
echo substr($str, 2, 4); // chen
echo substr($str, -4); // yang
支援位移與長度限制,適合關鍵字密度分析。
$talk = "I am certain that we could...";
$words = explode(' ', $talk);
foreach ($words as $w) {
echo "$w 出現 " . substr_count($talk, $w) . " 次<br>";
}
指定起始位置與長度替換,常用於**手機號碼遮罩、身分證遮罩**。
$phone = "15926841384";
echo substr_replace($phone, '****', 3, 4); // 159****1384
| 任務 | 首選函數 | 避免使用 | 備註 |
|---|---|---|---|
| 固定分隔符分割 | explode | preg_split | 速度差 5~10 倍 |
| 陣列合併字串 | implode | 迴圈串接 | 記憶體與速度雙贏 |
| 關鍵字取代 | str_replace | preg_replace | 無正則開銷 |
| 子字串搜尋位置 | strpos/stripos | preg_match | 單純搜尋無需正則 |
| 統計出現次數 | substr_count | preg_match_all | 極速 |
| 區間取代/遮罩 | substr_replace | 正則捕獲組 | 語意清晰 |
**原則**:除非涉及**複雜模式匹配**(如郵箱格式驗證、HTML 標籤屬性提取),**優先使用上述原生函數**,代碼更簡潔、執行更快、維護更易。