Instance
Calculate the number of occurrences of "world" in a string:
<?phpecho substr_count ("Hello World.") The world was nice "and" world "); >
The Substr_count () function calculates the number of occurrences of a substring in a string.
Note: Substrings are case-sensitive.
Note: This function does not count overlapping substrings (see Example 2).
Note: If the start parameter plus the length parameter is greater than the string size, the function generates a warning (see Example 3).
Grammar
Substr_count (String,substring,start,length)
parameters |
description |
string |
required. Specifies the string to check. |
substring |
required. Specifies the string to retrieve. |
start |
optional. Specifies where to start the search in the string. |
length |
optional. Specifies the length of the search. |
Technical details
return value: |
Returns the number of occurrences of a substring in a string. |
PHP version: |
4 + |
Update log: |
In PHP 5.1, the start and length parameters have been added. |
More examples
Example 1
Use all the parameters:
<?php$str = "This was nice"; Echo strlen ($STR). " <br> "; Using strlen () to return the string Lengthecho substr_count ($str, ' is '). " <br> "; The number of the Times ' is ' occurs in the Stringecho substr_count ($str, ' is ', 2). " <br> "; The string is now reduced to ' is is PHP ' echo substr_count ($str, "is", 3). " <br> "; The string is now reduced to "s was PHP" Echo substr_count ($str, "is", 3, 3). " <br> "; The string is now reduced to "s I"?>
Example 2
Overlapping sub-strings:
<?php$str = "Abcabcab"; Echo Substr_count ($str, "Abcab"); This function does not count overlapped substrings?>
Example 3
If the start and length arguments exceed the string length, the function outputs a warning:
<?phpecho $str = "This was nice"; Substr_count ($str, ' is ', 3,9);? >
Because the length value exceeds the length of the string (3 + 9 is greater than 12). So this will output a warning.
Example:
<?php$text = ' This is a test '; Echo strlen ($text). ' <br/> '; Output echo substr_count ($text, ' is '). ' <br/> '; 2//The string is reduced to's a test ', so it prints 1echo substr_count ($text, ' is ', 3). ' <br/> ';//is actually starting from the fourth character to find out if $text contains is//the text was reduced to ' re ', so it prints 0echo substr_count ($text, ' was ', 16, 3). ' <br/> '; The text is reduced to ' s I ', so it prints 0echo substr_count ($text, ' is ', 3, 3); Generates a warning because 5+10 > 14echo substr_count ($text, ' is ', 5, 10). ' <br/> '; Prints only 1, because it doesn ' t count overlapped subtrings$text2 = ' gcdgcdgcd '; Echo substr_count ($text 2, ' GCDGCD '). ' <br/> ';?