函式名:substr_count()
適用版本:PHP 4 >= 4.0.5, PHP 5, PHP 7
函式描述:substr_count() 函式用於計算字串中一個子字串出現的次數。
語法:int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
引數:
- $haystack:要在其中搜尋的字串。
- $needle:要搜尋的子字串。
- $offset(可選):從字串的第 offset 個字元開始搜尋,預設為 0。
- $length(可選):指定要搜尋的字元數,預設搜尋整個字串。
返回值:返回子字串在字串中出現的次數,如果沒有出現則返回 0。
示例 1:
$str = 'Hello, World!';
$count = substr_count($str, 'o');
echo $count; // 輸出 2
示例 2:
$str = 'abcdeabcdeabcde';
$count = substr_count($str, 'abc', 2, 6);
echo $count; // 輸出 2
上述示例中,substr_count() 函式在示例 1 中計算了字串 "Hello, World!" 中字母 "o" 的出現次數,結果為 2。在示例 2 中,它計算了字串 "abcdeabcdeabcde" 中從索引位置 2 開始的 6 個字元中子字串 "abc" 的出現次數,結果同樣為 2。