The substr_count() function counts the occurrence of a substring. The substr_count() function is case-sensitive.
PHP substr_count() Function has the following syntax.
substr_count(string,substring,start,length)
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to check |
substring | Required. | String to search for |
start | Optional. | Where in string to start searching |
length | Optional. | Length of the search |
PHP substr_count() Function returns the the number of times the substring occurs in the string.
Count the number of times "world" occurs in the string:
<?php
echo substr_count("Hello world. The world is nice","world");
echo "\n";
$myString = "I say, PHP, PHP, and PHP!";
echo substr_count( $myString, "PHP" );
?>
The code above generates the following result.
Using all parameters:
<?php
$str = "This is from java2s.com. Yes it is.";
echo strlen($str)."\n"; // Using strlen() to return the string length
echo substr_count($str,"is")."\n"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."\n";
echo substr_count($str,"is",3)."\n";
echo substr_count($str,"is",3,3)."\n";
?>
The code above generates the following result.
Overlapped substrings:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
The code above generates the following result.
If the start and length parameters exceeds the string length, substr_count will output a warning:
<?php
echo $str = "This is PHP";
substr_count($str,"is",3,9);
?>
This will output a warning because the length value exceeds the string length (3+9 is greater than 11).
The code above generates the following result.