substr_count
Calculate the number of occurrences of substrings
substr_count()
function calculates the number of times a substring appears in a string.
Comment: Substrings are case sensitive.
Note: This function does not count overlapping substrings (see Example 3).
Note: If the start parameter plus length parameter is greater than the string length, the function generates a warning (see Example 4).
Calculate the number of times "Shanghai" appears in a string:
<?php echo substr_count ( "I love Shanghai. Shanghai is the biggest city in china." , "Shanghai" ) ; ?>
Try it yourself
Use all parameters:
<?php $str = "This is nice" ; echo strlen ( $str ) . "<br>" ; // Use strlen() to return the string length echo substr_count ( $str , "is" ) . "<br>" ; // Number of times "is" appears 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 "si" ?>
Try it yourself
Overlapping substrings:
<?php $str = "abcabcab" ; echo substr_count ( $str , "abcab" ) ; // This function does not count overlapping substrings ?>
Try it yourself
If the start and length parameters exceed the string length, the function outputs 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 is outputted using it.
substr_count ( string , substring , start , length )
parameter | describe |
---|---|
string | Required. Specifies the string to be checked. |
Substring | Required. Specifies the string to search. |
start | Optional. Specifies where to start searching in the string. |
length | Optional. Specify the length of the search. |