萬盛學電腦網

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

PHP strpos() 尋找字串位置完整指南:嚴格比較、多位元組支援與效能優化

前言

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);
?>

進階參數:offset 從指定位置開始搜尋

<?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] (重疊匹配)
?>

大小寫不敏感搜尋:stripos()

<?php
$haystack = "Hello World";
$needle = "world";

echo strpos($haystack, $needle);   // false (區分大小寫)
echo stripos($haystack, $needle);  // 6 (不區分大小寫)

// 效能:stripos 略慢於 strpos,但通常可忽略
?>

多位元組字元支援:mb_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 (簡單搜尋)
// 複雜模式才用正則
?>

實務應用模式

1. 關鍵字過濾/審核

<?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)) {
    // 拒絕或標記審核
}
?>

2. 字串截取前綴/後綴

<?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
?>

3. CSV/TSV 欄位快速定位

<?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 表示未找到,兩者 == 比較皆為 true
  • 中文/多語言:必須用 mb_strpos() / mb_stripos() 指定編碼
  • 效能:簡單搜尋用 strpos(),複雜模式才用正則
  • PHP 8.0+:新增 str_starts_with()/str_ends_with()/str_contains() 更直觀
copyright © 萬盛學電腦網 all rights reserved