萬盛學電腦網

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

PHP strpos() 尋找子字串位置:三種回傳值型別完整解析

前言

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
找到在開頭0integertrue ❌false ✅true ✅
找到在中間/結尾>0integerfalse ✅false ✅true ✅
未找到falsebooleantrue ✅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+
?>

多位元組版本:mb_strpos()

<?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(...)) !== false
  • 大量重複搜尋同一 haystack:考慮建立索引或用更高演算法
  • 超長字串(>1MB):考慮分塊處理或串流搜尋

總結

  • strpos() 回傳 int (>=0) 或 false,0 和 false 均為 falsy
  • 必須使用 === false 或 !== false 嚴格比較
  • 位置 0 表示「在開頭找到」,非「未找到」
  • PHP 8.0+ 推薦 str_contains() 判斷存在性,str_starts_with()/str_ends_with() 判斷前綴/後綴
  • 中文等多位元組字串必須用 mb_strpos() 指定編碼
  • 封裝 safeStrpos() 回傳 int|null 可消除型別困擾
copyright © 萬盛學電腦網 all rights reserved