strpos() 尋找子字串在字串中首次出現的位置(0 起算)。因回傳 0 (找到在開頭) 或 false (未找到) 兩種型別,必須用 === 嚴格比較,是 PHP 新手最常踩的坑。
<?php
$haystack = "Hello world!";
$needle = "wo";
$pos = strpos($haystack, $needle);
echo $pos; // 6
// ❌ 錯誤寫法:鬆散比較
if ($pos == false) { // 0 == false 為 true!
echo "未找到";
} else {
echo "找到位置: $pos";
}
// ✅ 正確寫法:嚴格比較
if ($pos === false) {
echo "未找到";
} else {
echo "找到位置: $pos";
}
// 更佳:直接用 !== false
if (($pos = strpos($haystack, $needle)) !== false) {
echo "找到位置: $pos";
}
?>
<?php
$haystack = "needle23423432";
$needle = "needle";
$pos1 = strpos($haystack, $needle); // 0 (開頭)
$pos2 = strpos("234$needle", $needle); // 3 (中間)
$pos3 = strpos("nothing here", $needle); // false (未找到)
var_dump($pos1, $pos2, $pos3);
/*
int(0)
int(3)
bool(false)
*/
// 嚴格比較測試
function testStrict(string $haystack, string $needle): void {
$pos = strpos($haystack, $needle);
echo "鬆散比較 (==): ";
var_dump($pos == false); // 0 == false → true ❌
echo "嚴格比較 (===): ";
var_dump($pos === false); // 0 === false → false ✅
}
testStrict($haystack, $needle);
?>
<?php
$str = "abcdefabcdef";
// 從位置 5 開始找
echo strpos($str, "abc", 5); // 6 (第二個 abc)
// 找出所有出現位置
function findAllPositions(string $haystack, string $needle): array {
$positions = [];
$offset = 0;
while (($pos = strpos($haystack, $needle, $offset)) !== false) {
$positions[] = $pos;
$offset = $pos + 1; // 避免無限迴圈(空字串 needle)
}
return $positions;
}
print_r(findAllPositions("ababa", "aba")); // [0, 2] (重疊匹配)
?>
<?php $haystack = "Hello World"; $needle = "world"; echo strpos($haystack, $needle); // false (區分大小寫) echo stripos($haystack, $needle); // 6 (不區分大小寫) // 效能:stripos 略慢於 strpos,但通常可忽略 ?>
<?php
$str = "你好世界";
$needle = "世";
// strpos 按位元組搜尋,中文會錯誤
var_dump(strpos($str, $needle)); // int(6) 位元組位置,非字元位置
// mb_strpos 正確處理多位元組
var_dump(mb_strpos($str, $needle, 0, 'UTF-8')); // int(2) 字元位置 ✅
// 完整參數
mb_strpos(
string $haystack,
string $needle,
int $offset = 0,
string $encoding = mb_internal_encoding()
): int|false
?>
<?php
$haystack = str_repeat("abcdefghijklmnopqrstuvwxyz ", 10000); // ~270KB
$needle = "xyz";
$iterations = 10000;
// strpos
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
strpos($haystack, $needle);
}
echo "strpos: " . (microtime(true) - $start) . "s\n";
// strstr (只需知道是否存在)
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
strstr($haystack, $needle);
}
echo "strstr: " . (microtime(true) - $start) . "s\n";
// preg_match (正則)
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
preg_match('/' . preg_quote($needle) . '/', $haystack);
}
echo "preg_match: " . (microtime(true) - $start) . "s\n";
// 通常:strpos ≈ strstr < preg_match (簡單搜尋)
// 複雜模式才用正則
?>
<?php
function containsForbiddenWords(string $text, array $forbidden): bool {
$lowerText = mb_strtolower($text);
foreach ($forbidden as $word) {
if (mb_strpos($lowerText, mb_strtolower($word)) !== false) {
return true;
}
}
return false;
}
$forbidden = ['badword1', 'badword2', 'spam'];
if (containsForbiddenWords($userInput, $forbidden)) {
// 拒絕或標記審核
}
?>
<?php
function startsWith(string $haystack, string $needle): bool {
return strpos($haystack, $needle) === 0;
}
function endsWith(string $haystack, string $needle): bool {
$len = strlen($needle);
return $len === 0 || substr($haystack, -$len) === $needle;
// 或 PHP 8.0+: str_ends_with($haystack, $needle)
}
// PHP 8.0+ 內建
var_dump(str_starts_with('hello world', 'hello')); // true
var_dump(str_ends_with('hello world', 'world')); // true
?>
<?php
function getCsvField(string $line, int $fieldIndex, string $delimiter = ','): string {
$start = 0;
for ($i = 0; $i <= $fieldIndex; $i++) {
$pos = strpos($line, $delimiter, $start);
if ($pos === false) {
if ($i === $fieldIndex) return substr($line, $start);
return '';
}
if ($i === $fieldIndex) {
return substr($line, $start, $pos - $start);
}
$start = $pos + 1;
}
return '';
}
?>
| 函數 | 用途 | 大小寫 | 多位元組版 |
|---|---|---|---|
strpos | 首次出現位置 | 敏感 | mb_strpos |
stripos | 首次出現位置 | 不敏感 | mb_stripos |
strrpos | 最後出現位置 | 敏感 | mb_strrpos |
strripos | 最後出現位置 | 不敏感 | mb_strripos |
strstr | 從找到處到結尾 | 敏感 | mb_strstr |
stristr | 從找到處到結尾 | 不敏感 | mb_stristr |
strpos() 結果必須用 === false 或 !== false 判斷0 表示找到在開頭,false 表示未找到,兩者 == 比較皆為 truemb_strpos() / mb_stripos() 指定編碼strpos(),複雜模式才用正則str_starts_with()/str_ends_with()/str_contains() 更直觀