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

PHP 字串查找函數:strstr、strpos、substr_count 完整指南

     編輯:PHP 綜合知識

字串查找是文本處理基礎操作,PHP 提供多種函數支援子字串定位、出現次數統計等需求,正確選擇關鍵在於「需要位置還是內容」與「大小寫敏感度」。

核心函數對照

函數功能回傳值大小寫敏感對應不敏感版
strstr()首次出現位置到末尾的子字串子字串 / false是stristr()
strpos()首次出現位置索引 (0 起)int / false是stripos()
strrpos()最後出現位置索引int / false是strripos()
substr_count()子字串出現次數int是-

strstr():獲取子字串到末尾

<?php
$email = 'user@example.com';
$domain = strstr($email, '@'); // '@example.com'
echo $domain;

// 只需檢查是否包含
if (strstr($haystack, $needle) !== false) { ... }
?>

strpos():精確定位索引(高頻使用)

<?php
$str = 'Hello World';
echo strpos($str, 'W');  // 6
echo strpos($str, 'x');  // false

// 嚴格判斷:必須用 !== false (0 也是 false)
if (strpos($str, 'H') !== false) { echo 'Found at 0'; }
?>

substr_count():統計出現次數

<?php
$text = 'ababababa';
echo substr_count($text, 'aba'); // 2 (不重疊計數)
echo substr_count($text, 'ab');  // 4
?>

進階查找:mbstring 多位元組支援

<?php
$str = '中文測試字串';
echo mb_strpos($str, '測試', 0, 'UTF-8'); // 6 (字符索引)
echo mb_substr($str, mb_strpos($str, '測試', 0, 'UTF-8')); // '測試字串'
?>

正則表達式查找:preg_match()

<?php
$pattern = '/\b\d{3}-\d{4}\b/'; // 電話號碼格式
$text = '聯繫電話:02-1234-5678';
if (preg_match($pattern, $text, $matches)) {
    echo $matches[0]; // 1234-5678
}
?>

效能與選擇指南

需求推薦函數理由
只需判斷是否包含strpos() !== false最快,短路返回
需獲取匹配後內容strstr()直接返回子字串
需精確位置索引strpos()數值索引便於後續截取
統計出現次數substr_count()專用優化
模式匹配/複雜規則preg_match()正則表達式威力
中文/多位元組mb_strpos() 等字符級正確

掌握各查找函數語義差異,避免「用 strstr 判斷包含」這類效能浪費,是 PHP 文本處理進階的標誌。

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