PHP substr_count() function

Example

Count the number of times "Shanghai" appears in the string:

<?php
echo substr_count("I love Shanghai. Shanghai is the biggest city in china.","Shanghai");
?>

Run Instance

The substr_count() function calculates the number of times the substring appears in the string.

Note:The substring is case-sensitive.

Note:This function does not count overlapping substrings (see example 2).

Note:If start The parameter plus length If the parameter is greater than the length of the string, the function generates a warning (see example 3).

Syntax

substr_count(string,substring,start,length)
Parameter Description
string Required. Specifies the string to be checked.
substring Required. Specifies the string to be searched.
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 times a substring appears in a 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 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 "s i"
?>

Run Instance

Example 2

Overlapping Substring:

<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapping substrings
?>

Run Instance

Example 3

If start and length A warning will be output if the parameter exceeds the length of the string:

<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>

A warning will be output if the length value exceeds the length of the string (3 + 9 is greater than 12).