PHP substr_count() 函数
实例
计算 "Shanghai" 在字符串中出现的次数:
<?php echo substr_count("I love Shanghai. Shanghai is the biggest city in china.","Shanghai"); ?>
substr_count() 函数计算子串在字符串中出现的次数。
注释:子串是区分大小写的。
注释:该函数不计数重叠的子串(参见例子 2)。
注释:If start 参数加上 length 参数大于字符串长度,则该函数生成一个警告(参见例子 3)。
语法
substr_count(string,substring,start,length)
参数 | 描述 |
---|---|
string | 必需。规定被检查的字符串。 |
substring | 必需。规定要搜索的字符串。 |
start | 可选。规定在字符串中何处开始搜索。 |
length | 可选。规定搜索的长度。 |
Technical Details
Return Value: | Returns the number of times the substring appears in the string. |
PHP Version: | 4+ |
Update Log: | In PHP 5.1, a new start and length Parameters. |
More Examples
Example 1
Use all parameters:
<?php $str = "This is nice"; echo strlen($str)."<br>"; // Use strlen() to return the length of the string echo substr_count($str,"is")."<br>"; // The number of occurrences of "is" in the string echo substr_count($str,"is",2)."<br>"; // The string is reduced to "is is nice" echo substr_count($str,"is",3)."<br>"; // The string is reduced to "s is nice" echo substr_count($str,"is",3,3)."<br>"; // The string is reduced to "s i" ?>
Example 2
Overlapping Substring:
<?php $str = "abcabcab"; echo substr_count($str,"abcab"); // This function does not count overlapping substrings ?>
Example 3
If start and length If the parameters exceed the length of the string, the function will output a warning:
<?php echo $str = "This is nice"; substr_count($str,"is",3,9); ?>
Because the length value exceeds the length of the string (3 + 9 is greater than 12), a warning will be output when used.