兩者皆用於尋找子字串,但回傳值與用途不同。選對函數能簡化邏輯。
falsestrstr($haystack, $needle, $before_needle = false)$email = 'user@example.com';
echo strstr($email, '@'); // 輸出:@example.com
echo strstr($email, '@', true); // PHP 5.3+ 參數 true:輸出 user
falsestrpos($haystack, $needle, $offset = 0)$pos = strpos('Hello world', 'wo'); // 回傳 6
if ($pos !== false) { ... } // 必須用 !== false,因為 0 也是合法位置
strpos() 最快(不建構子字串)strstr() 一步到位stripos()/stristr() 略慢於區分大小寫版本// ❌ 錯誤:0 會被視為 false
if (strpos($str, 'abc')) { ... }
// ✅ 正確:嚴格比較
if (strpos($str, 'abc') !== false) { ... }
若專案使用 UTF-8,建議改用 mb_strpos()、mb_strstr() 避免位置偏移錯誤。