前言
本文延續 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)
?>
回傳型別決策表
| 搜尋結果 | 回傳值 | gettype() | 正確判斷 |
| 找到,位置 > 0 | 正整數 | integer | !== false |
| 找到,位置 = 0 | 0 | integer | !== false |
| 未找到 | false | 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 程式設計有所幫助。
- 上一篇文章: PHP 尋找字串位置:strpos() 函數用法、回傳值陷阱與嚴格比較
- 下一篇文章: PHP 移除字串首尾空白:trim()、ltrim()、rtrim()、chop() 完整比較
Copyright ©
程式碼之家 All Rights Reserved