字串查找是文字處理的基石。PHP 提供豐富的搜尋函數族群,按功能可分為:子字串提取、出現次數統計、位置定位 三大類。本文系統解析各函數語法、差異與實戰陷阱。
strstr(string $haystack, string $needle): string|false
strrchr(string $haystack, string $needle): string|false
| 函數 | 搜尋方向 | 返回內容 | 典型用途 |
|---|---|---|---|
| strstr() | 從左向右(首次出現) | 從匹配位置到字串結尾 | 提取郵箱域名、URL 路徑等 |
| strrchr() | 從右向左(最後出現) | 從匹配位置到字串結尾 | 提取檔案副檔名、最後路徑段 |
<?php
$a = "p";
$b = "echo是php函數,p是html標記";
$str1 = strstr($b, $a); // 從第一個 p 開始
// 輸出: "p是php函數,p是html標記"
$str2 = strrchr($b, $a); // 從最後一個 p 開始
// 輸出: "p是html標記"
if ($str1) echo $str1 . "<br>";
else echo "找不到 p<br>";
if ($str2) echo $str2;
else echo "找不到 p";
?>
stristr():strstr() 不區分大小寫版本strchr():strstr() 別名substr_count(string $haystack, string $needle, int $offset = 0, int|null $length = null): int
$offset:搜尋起始位置(可為負數,從末尾倒數)$length:搜尋長度限制<?php
$str = "this is a test";
echo substr_count($str, 'is') . '<br>'; // 2 (全字串)
echo substr_count($str, 'is', 3) . '<br>'; // 1 (從索引3開始: "s is a test")
echo substr_count($str, 'is', 3, 3) . '<br>'; // 0 (從索引3長度3: "s i")
?>
strpos(string $haystack, string $needle, int $offset = 0): int|false
strrpos(string $haystack, string $needle, int $offset = 0): int|false
| 特性 | strpos() | strrpos() |
|---|---|---|
| 搜尋方向 | 左→右(首次) | 右→左(最後) |
| $needle 類型 | 字串(可多字元) | 單字元(多字元僅取首字元) |
| 返回值 | 索引位置(0起) | 索引位置(0起) |
| 未找到 | false | false |
<?php
$text = "php語言...";
$pos = strpos($text, "php"); // 返回 0 (索引0)
// ❌ 錯誤判斷
if ($pos) { ... } // 0 被視為 false,邏輯錯誤!
// ✅ 正確判斷:使用 !== false
if ($pos !== false) {
echo "找到位置: $pos";
}
?>
鐵律:所有返回索引的函數必須用 !== false 或 === false 判斷。
<?php
$text = "php語言和asp語言的區別之一:php更加穩定安全";
// strrpos 找字串 "php" -> 僅取首字元 'p' 找最後位置
$str1 = strrpos($text, "php"); // 實際找 'p' 最後位置
// strpos 正確找字串 "php" 首次位置
$str2 = strpos($text, "php"); // 正確找 "php" 首次位置
?>
<?php
function parseEmail($email) {
// 提取用戶名(@ 之前)
$user = strstr($email, '@', true); // PHP 5.3+ 第三參數 true 返回匹配前部分
// 提取域名(@ 之後)
$domain = substr(strstr($email, '@'), 1); // 截掉 @
// 統計點號數量(子域名層級)
$dotCount = substr_count($domain, '.');
// 定位最後一個點(頂級域名分隔)
$lastDot = strrpos($domain, '.');
$tld = substr($domain, $lastDot + 1);
return compact('user', 'domain', 'dotCount', 'tld');
}
print_r(parseEmail("user.name@sub.example.com"));
/*
Array (
[user] => user.name
[domain] => sub.example.com
[dotCount] => 2
[tld] => com
)
*/
?>
| 需求 | 推薦函數 | 備註 |
|---|---|---|
| 檢查是否包含子串 | str_contains() (PHP 8+) | 返回 bool,語義最清晰 |
| 獲取首次位置 | strpos() | 必用 !== false 判斷 |
| 獲取最後位置 | strrpos() | 單字元搜尋 |
| 提取首次匹配後內容 | strstr() | 第三參數 true 獲取前段 |
| 提取最後匹配後內容 | strrchr() | 適用副檔名提取 |
| 統計出現次數 | substr_count() | 支援偏移長度限制 |
| 大小寫不敏感搜尋 | stripos()/stristr() | 對應不敏感版本 |
| 多模式搜尋 | preg_match() | 正則表達式場景 |
掌握字串搜尋函數的搜尋方向、返回值語義、參數限制是避坑關鍵。現代 PHP (8+) 推薦優先使用 str_contains()、str_starts_with()、str_ends_with() 等語義化函數,複雜模式轉用 PCRE 正則,構建可維護的文字處理邏輯。