strpos() 回傳值有三種可能:int >= 0 (找到位置)、0 (找到在開頭)、false (未找到)。本文深入解析三種情況並提供防錯模式。
<?php $haystack1 = "2349534134345w3mentor16504381640386488129"; // 中間 $haystack2 = "w3mentor234953413434516504381640386488129"; // 開頭 $haystack3 = "center234953413434516504381640386488129fyi"; // 不存在 $pos1 = strpos($haystack1, "w3mentor"); $pos2 = strpos($haystack2, "w3mentor"); $pos3 = strpos($haystack3, "w3mentor"); echo "pos1 = ($pos1); type is " . gettype($pos1) . "\n"; // int echo "pos2 = ($pos2); type is " . gettype($pos2) . "\n"; // int (0) echo "pos3 = ($pos3); type is " . gettype($pos3) . "\n"; // boolean (false) // 關鍵:pos2 是 0 (整數),pos3 是 false (布林) ?>
| 情況 | 回傳值 | 型別 | == false | === false | !== false |
|---|---|---|---|---|---|
| 找到在開頭 | 0 | integer | true ❌ | false ✅ | true ✅ |
| 找到在中間/結尾 | >0 | integer | false ✅ | false ✅ | true ✅ |
| 未找到 | false | boolean | true ✅ | true ✅ | false ✅ |
<?php
// 模式 1:嚴格比較(推薦)
$pos = strpos($haystack, $needle);
if ($pos === false) {
// 未找到
} else {
// 找到,位置為 $pos (可能為 0)
}
// 模式 2:賦值同時判斷(最常用)
if (($pos = strpos($haystack, $needle)) !== false) {
// 找到,$pos 可直接使用
echo "位置: $pos";
} else {
// 未找到
}
// 模式 3:PHP 8.0+ str_contains() 只需布林結果
if (str_contains($haystack, $needle)) {
// 找到
}
// 但無法取得位置
?>
<?php
/**
* 安全版 strpos,永遠回傳 int|null
*/
function safeStrpos(string $haystack, string $needle, int $offset = 0): ?int {
$pos = strpos($haystack, $needle, $offset);
return $pos === false ? null : $pos;
}
/**
* 檢查是否包含子字串(語意更清晰)
*/
function contains(string $haystack, string $needle): bool {
return strpos($haystack, $needle) !== false;
}
/**
* 找出所有出現位置
*/
function strposAll(string $haystack, string $needle, int $offset = 0): array {
$positions = [];
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$positions[] = $pos;
$offset = $pos + 1;
}
return $positions;
}
// 使用
$pos = safeStrpos($haystack, $needle);
if ($pos !== null) {
echo "找到於位置 $pos";
}
?>
<?php
// ❌ 錯誤 1:用 == false
if (strpos($a, $b) == false) { ... } // 位置 0 會誤判為未找到
// ❌ 錯誤 2:用 !strpos()
if (!strpos($a, $b)) { ... } // 位置 0 會被 !0=true 誤判為未找到
// ❌ 錯誤 3:直接當布林用
if (strpos($a, $b)) { ... } // 位置 0 為 falsy,誤判
// ❌ 錯誤 4:isset() 檢查
if (isset(strpos($a, $b))) { ... } // 永遠 true,isset 檢查變數非 null
// ✅ 正確模式
if (strpos($a, $b) !== false) { ... }
if (($pos = strpos($a, $b)) !== false) { ... }
if (str_contains($a, $b)) { ... } // PHP 8.0+
?>
<?php
$str = "你好世界PHP";
$needle = "世";
// strpos 回傳位元組位置
var_dump(strpos($str, $needle)); // int(6) - UTF-8 中 "你好" 佔 6 位元組
// mb_strpos 回傳字元位置
var_dump(mb_strpos($str, $needle, 0, 'UTF-8')); // int(2) - 第 3 個字元 ✅
// 同樣需要嚴格比較
$pos = mb_strpos($str, $needle, 0, 'UTF-8');
if ($pos !== false) { ... }
?>
str_contains() (PHP 8.0+) 或 strpos() !== false($pos = strpos(...)) !== falsestrpos() 回傳 int (>=0) 或 false,0 和 false 均為 falsy=== false 或 !== false 嚴格比較str_contains() 判斷存在性,str_starts_with()/str_ends_with() 判斷前綴/後綴mb_strpos() 指定編碼safeStrpos() 回傳 int|null 可消除型別困擾