萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 字串查找完全指南:strstr、strpos、substr_count 等核心函數實戰解析

PHP 字串搜尋函數體系概覽

字串查找是文字處理的基石。PHP 提供豐富的搜尋函數族群,按功能可分為:子字串提取、出現次數統計、位置定位 三大類。本文系統解析各函數語法、差異與實戰陷阱。

子字串提取:strstr() vs strrchr()

函數簽名

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()、strchr()

  • stristr():strstr() 不區分大小寫版本
  • strchr():strstr() 別名

出現次數統計:substr_count()

函數簽名

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() vs strrpos()

函數簽名對比

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起)
未找到falsefalse

⚠️ 致命陷阱:0 與 false 混淆

<?php
$text = "php語言...";
$pos = strpos($text, "php");  // 返回 0 (索引0)

// ❌ 錯誤判斷
if ($pos) { ... }  // 0 被視為 false,邏輯錯誤!

// ✅ 正確判斷:使用 !== false
if ($pos !== false) {
    echo "找到位置: $pos";
}
?>

鐵律:所有返回索引的函數必須用 !== false 或 === false 判斷。

strrpos() 字串限制實測

<?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 正則,構建可維護的文字處理邏輯。

copyright © 萬盛學電腦網 all rights reserved