函數原型
int substr_count(string $haystack, string $needle, int $offset = 0, int $length = null)
參數說明
$haystack:被搜尋的字串 (乾草堆)
$needle:要搜尋的子字串 (針)
$offset:起始位移 (負值從末尾倒數)
$length:搜尋長度 (負值表示到末尾前幾字元)
基本範例
<?php
$str = 'ni hao ,wo jiao wang hui ,lai zi an hui chao hu';
echo '原字串: ' . $str . '<br>';
// 全字串搜尋 'i'
echo '出現次數: ' . substr_count($str, 'i') . '<br>'; // 4
// 從位移 6 開始搜尋
echo '從第 6 字元起: ' . substr_count($str, 'i', 6) . '<br>'; // 3
// 從位移 6 開始,長度 20
echo '從第 6 字元長度 20: ' . substr_count($str, 'i', 6, 20) . '<br>'; // 2
?>
進階用法
計算單字出現次數 (配合單字邊界)
<?php
$text = 'the quick brown fox jumps over the lazy dog. the dog sleeps.';
// 簡易版:空格分隔 (實務建議用正則 \bthe\b)
$words = explode(' ', strtolower($text));
$count = 0;
foreach ($words as $w) {
if (rtrim($w, '.,!?') === 'the') $count++;
}
echo "the 出現 $count 次"; // 3
?>
計算 HTML 標籤出現次數
<?php
$html = '<div><p>Hello</p><p>World</p></div>';
echo 'p 標籤數: ' . substr_count($html, '<p>'); // 2
echo '/p 標籤數: ' . substr_count($html, '</p>'); // 2
?>
多位元組字串 (UTF-8 中文) 注意事項
<?php
$str = '測試測試測試';
echo substr_count($str, '測'); // 3 (正確,因為 '測' 在 UTF-8 中不會被拆分)
echo substr_count($str, '試'); // 3
// 但若搜尋多位元組字元組合需謹慎
$str2 = '😀😀😀'; // Emoji (4 bytes each)
echo substr_count($str2, '😀'); // 3 (PHP 7+ 正確處理)
?>
效能與替代方案
| 需求 | 推薦函數 | 備註 |
| 單一字元/子字串計數 | substr_count() | C 層實作,最快 |
| 正則模式計數 | preg_match_all() | 功能強大但較慢 |
| 單字計數 (含邊界) | str_word_count() + 陣列統計 | 支援多語言 |
| 大檔案流式計數 | fgets() + substr_count() 迴圈 | 避免一次載入整檔 |
常見錯誤
$offset 超出字串長度 → 回傳 0 (不報錯)。
$length 為負值時意義不同:從末尾往前算。
- 大小寫敏感:
substr_count('ABC', 'a') 回傳 0,需自行 strtolower()。