PHP substr_count() Function
The PHP substr_count() function returns the number of occurrences of specified substring in the specified string.
Note: The substring is case-sensitive. This function doesn't count overlapped substrings (see the example below).
Syntax
substr_count(string, substring, offset, length)
Parameters
string |
Required. Specify the input string. |
substring |
Required. Specify the substring to search for. |
offset |
Optional. Specify offset parameter which indicates where to start counting in the string. If it is negative, counting starts from the end of the string. |
length |
Optional. Specify the maximum length after the specified offset to search for the substring. It generates a warning if the offset plus the length is greater than the string length. A negative length counts from the end of string. |
Return Value
Returns the number of occurrences of substring in the string.
Example:
In the example below, this function is used to find out the number of occurrences of given substring in the given string.
<?php $str = "This is an island."; //number of occurrences of 'is' in the string echo "1. ".substr_count($str, 'is')."\n"; //the string is reduced to 's is an island.' //therefore returns 2 echo "2. ".substr_count($str, 'is', 3)."\n"; //the string is reduced to 's an island.' //therefore returns 1 echo "3. ".substr_count($str, 'is', 6)."\n"; //the string is reduced to 's i' //therefore returns 0 echo "4. ".substr_count($str, 'is', 3, 3)."\n"; ?>
The output of the above code will be:
1. 3 2. 2 3. 1 4. 0
Example:
Consider the example below which illustrates on function behavior with overlapped substrings. The function doesn't count overlapped substrings.
<?php $str = "ABCABCABC"; //number of occurrences of 'ABCABC' in the string echo substr_count($str, 'ABCABC'); ?>
The output of the above code will be:
1
Example:
When the offset plus the length parameter is greater than the string length, the function generates a warning. Consider the example below.
<?php $str = "ABCABCABC"; //string length echo "string length: ".strlen($str)."\n"; //generates a warning because 3+10 > 9 echo substr_count($str, 'ABCABC', 3, 10); ?>
The output of the above code will be:
string length: 9 PHP Fatal error: Uncaught ValueError: substr_count(): Argument #4 ($length) must be contained in argument #1 ($haystack) in Main.php:8 Stack trace: #0 Main.php(8): substr_count() #1 {main} thrown in Main.php on line 8
❮ PHP String Reference