PHP 提供 strstr、stristr、strpos 三個函數用於在字串中查找子字串,三者回傳值型態、大小寫敏感度與效能各有不同,選用時需依據需求決定。
string strstr ( string $haystack, mixed $needle [, bool $before_needle = false ] )
$haystack 中從 $needle 第一次出現處到字串結尾的部分。false。$before_needle 為 true,則回傳 $needle 之前的部分(PHP 5.3.0+)。<?php $email = 'yuxiaoxiao@example.com'; $domain = strstr($email, '@'); // 回傳 @example.com $user = strstr($email, '@', true); // 回傳 yuxiaoxiao (PHP 5.3.0+) ?>
string stristr ( string $haystack, mixed $needle [, bool $before_needle = false ] )
strstr,但不區分大小寫。<?php
echo stristr("Hello world!", "WORLD"); // 輸出 world!
?>
int strpos ( string $haystack, mixed $needle [, int $offset = 0 ] )
$needle 在 $haystack 中首次出現的數值位置(從 0 起算)。false。stripos()。strpos,記憶體佔用少、速度快。=== false。<?php
echo strpos("Hello world!", "wo"); // 輸出 6
?>
| 函數 | 大小寫敏感 | 回傳值 | 適用場景 |
|---|---|---|---|
| strstr | 是 | 子字串 (從匹配處到結尾) / false | 需取得匹配後內容 |
| stristr | 否 | 子字串 / false | 不分大小寫搜尋並取得後續內容 |
| strpos | 是 | 整數位置 / false | 僅判斷是否存在、效能優先 |
| stripos | 否 | 整數位置 / false | 不分大小寫判斷是否存在 |
strstr(區分大小寫)或 stristr(不區分)。strpos(區分大小寫)或 stripos(不區分),記得用 === false 判斷失敗。strpos 可能誤判,建議改用 mb_strpos 或正則表達式。