核心函式:substr_count()
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
$haystack:母字串
$needle:要搜尋的子字串
$offset:起始位移(可選)
$length:搜尋長度(可選)
實戰範例
$str = "this is a test";
echo substr_count($str, 'is'); // 2
echo substr_count($str, 'is', 3); // 1 (從第 3 字元開始)
echo substr_count($str, 'is', 3, 3); // 0 (從第 3 字元起長度 3)
$str2 = 'https://www.bkjia.com 愛程序網_軟件編程入門教程_軟件設計交流_字符出現次數';
echo substr_count($str2, 'w'); // 3
echo substr_count($str2, 't'); // 2
echo substr_count($str2, '愛程序網'); // 1
常用字串搜尋函式對照表
| 函式 | 說明 | 大小寫敏感 |
| strstr | 尋找首次出現位置,回傳子字串 | 是 |
| stristr | strstr 不分大小寫版本 | 否 |
| strpos | 尋找首次出現位置(整數索引) | 是 |
| stripos | strpos 不分大小寫版本 | 否 |
| strrpos | 尋找最後一次出現位置 | 是 |
| strripos | strrpos 不分大小寫版本 | 否 |
| strrchr | 尋找字元最後一次出現,回傳子字串 | 是 |
| substr | 擷取子字串 | — |
效能提示
- 單純計數用
substr_count 最快;
- 需位置資訊用
strpos/stripos;
- 大字串頻繁搜尋考慮建立索引或使用全文搜尋引擎。