substr_count()函數(shù)用于計算子串在字符串中出現(xiàn)的次數(shù)。
substr_count(string,substring,start,length)
substr_count() 返回子字符串 substring 在字符串 string 中出現(xiàn)的次數(shù)。注意 substring 區(qū)分大小寫。
函數(shù)返回整型。它返回子字符串在字符串中出現(xiàn)的次數(shù)。
| 序號 | 參數(shù)與說明 |
|---|---|
| 1 | string 指定在此字符串中進行搜索。 |
| 2 | substring 用于指定要搜索的字符串 |
| 3 | start 它指定何時在字符串中開始搜索,開始計數(shù)的偏移位置。如果是負(fù)數(shù),就從字符的末尾開始統(tǒng)計。 |
| 4 | length 它指定字符串的長度 |
試試下面的實例,計算 "krishna" 在字符串中出現(xiàn)的次數(shù):
<?php
//計算 "krishna" 在字符串中出現(xiàn)的次數(shù)
echo substr_count("sairamkrishna","krishna");
echo '<br>';
$text = 'This is a test';
echo strlen($text); // 14
echo '<br>';
echo substr_count($text, 'is'); // 2
echo '<br>';
// 字符串被簡化為 's is a test',因此輸出 1
echo substr_count($text, 'is', 3);
echo '<br>';
// 字符串被簡化為 's i',所以輸出 0
echo substr_count($text, 'is', 3, 3);
echo '<br>';
// 輸出 1,因為該函數(shù)不計算重疊字符串
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcd');
echo '<br>';
// 因為 5+10 > 14,所以生成警告
echo substr_count($text, 'is', 5, 10);
?>測試看看?/?輸出結(jié)果
1 14 2 1 0 3 PHP Warning: substr_count(): Invalid length value in...