首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 在字串中搜尋子字串:strpos() 進階用法與回傳型別分析

     編輯:PHP 相關知識

前言

本文延續 strpos() 基礎用法,重點分析不同位置搜尋結果的回傳型別差異(整數 vs 布林),並示範多字串批次搜尋模式。

多種位置搜尋結果對照

<?php
$haystack1 = "2349534134345w3mentor16504381640386488129"; // 中間
$haystack2 = "w3mentor234953413434516504381640386488129"; // 開頭
$haystack3 = "center234953413434516504381640386488129fyi"; // 不存在

$pos1 = strpos($haystack1, "w3mentor");
$pos2 = strpos($haystack2, "w3mentor");
$pos3 = strpos($haystack3, "w3mentor");

echo "pos1 = ($pos1); type: " . gettype($pos1) . "\n"; // pos1 = (13); type: integer
echo "pos2 = ($pos2); type: " . gettype($pos2) . "\n"; // pos2 = (0); type: integer
echo "pos3 = ($pos3); type: " . gettype($pos3) . "\n"; // pos3 = (); type: boolean (false)
?>

回傳型別決策表

封裝通用搜尋函數

<?php
function searchSubstring(string $haystack, string $needle): array {
    $pos = strpos($haystack, $needle);
    return [
        'found'   => $pos !== false,
        'position'=> $pos,           // false 或整數
        'type'    => gettype($pos),  // 'integer' 或 'boolean'
    ];
}

$tests = [
    ["abcde", "bc"],
    ["abcde", "a"],
    ["abcde", "f"],
];

foreach ($tests as [$h, $n]) {
    $r = searchSubstring($h, $n);
    echo "在 '$h' 搜尋 '$n' => ";
    echo $r['found'] ? "找到,位置 {$r['position']}" : "未找到";
    echo " (型別: {$r['type']})\n";
}
?>

效能與替代方案

  • 單純判斷是否存在:PHP 8 str_contains()、舊版 strpos() !== false。
  • 大小寫不敏感:stripos()。
  • 正則表達式搜尋:preg_match() 可擷取群組、支援複雜模式。
  • 多關鍵字同時搜尋:preg_match() 配合 | 或建立 Aho-Corasick 自動機(大量關鍵字)。

總結

理解 strpos() 回傳 0 (integer) 與 false (boolean) 的型別差異,是避免「找到卻判斷為未找到」Bug 的關鍵。封裝統一介面可提升程式碼可讀性。希望本文對您的 PHP 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
搜尋結果回傳值gettype()正確判斷
找到,位置 > 0正整數integer!== false
找到,位置 = 00integer!== false
未找到falseboolean=== false