首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 字串處理避開正則 10 大高效函數實戰指南

     編輯:PHP 綜合知識

正則表達式功能強大但**效能較差、可讀性低**。PHP 內建大量字串函數能以**原生速度**完成分割、搜尋、取代、統計等常見任務。本文精選 10 大函數,附真實場景範例與效能建議,助你寫出更快、更維護的代碼。

一、strtok() — 依字元集合切割(詞法分析)

連續呼叫、內部維持指標,適合解析固定分隔符的結構化字串(如 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
}

二、explode() — 依單一分隔符分割成陣列

**比 preg_split、split 快數倍**,首選分割工具。

$summary = "In the latest installment...";
$words = explode(' ', strip_tags($summary));
echo "單字數:" . count($words);

三、implode() — 陣列合併為字串

explode 逆操作,高效組合 SQL IN 列表、CSV 匯出等。

$cities = ["Chengdu","Chongqing","Beijing","Shanghai","Guangzhou"];
echo implode('|', $cities); // Chengdu|Chongqing|Beijing|Shanghai|Guangzhou

四、strpos() / stripos() — 尋找子字串首次位置

區分大小寫用 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);

五、strrpos() — 尋找子字串最後位置

常用於**截取摘要至最近單字結尾**,避免硬切單字。

$limit = 100;
$summary = "長文章內容...";
if (strlen($summary) > $limit) {
    $summary = substr($summary, 0, strrpos(substr($summary, 0, $limit), ' ')) . '...';
}

六、str_replace() — 批次取代(支援陣列)

**比 preg_replace 快得多**,適用關鍵字過濾、模板變數替換、Email 反爬蟲。

$email = "lvchenyang@live.cn";
echo str_replace('@', ' (at) ', $email); // lvchenyang (at) live.cn

七、strstr() / stristr() — 取得子字串首次出現處至結尾

搭配 ltrim() 可快速取得 Email 域名、URL 路徑等。

$url = "user@example.com";
echo ltrim(strstr($url, '@'), '@'); // example.com

八、substr() — 依位移/長度切片

支援負數位移(從末尾算起),極靈活。

$str = "lvchenyang";
echo substr($str, 2, 4);  // chen
echo substr($str, -4);    // yang

九、substr_count() — 統計子字串出現次數

支援位移與長度限制,適合關鍵字密度分析。

$talk = "I am certain that we could...";
$words = explode(' ', $talk);
foreach ($words as $w) {
    echo "$w 出現 " . substr_count($talk, $w) . " 次<br>";
}

十、substr_replace() — 區間取代

指定起始位置與長度替換,常用於**手機號碼遮罩、身分證遮罩**。

$phone = "15926841384";
echo substr_replace($phone, '****', 3, 4); // 159****1384

效能與選用總結表

任務首選函數避免使用備註
固定分隔符分割explodepreg_split速度差 5~10 倍
陣列合併字串implode迴圈串接記憶體與速度雙贏
關鍵字取代str_replacepreg_replace無正則開銷
子字串搜尋位置strpos/stripospreg_match單純搜尋無需正則
統計出現次數substr_countpreg_match_all極速
區間取代/遮罩substr_replace正則捕獲組語意清晰

**原則**:除非涉及**複雜模式匹配**(如郵箱格式驗證、HTML 標籤屬性提取),**優先使用上述原生函數**,代碼更簡潔、執行更快、維護更易。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved