Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP substr_count() Function

PHP substr_count() Function

PHP String Reference Manual PHP String Reference Manual

Example

Count the number of occurrences of "world" in a string:

Run Example »


The substr_count() function counts the number of occurrences of a substring in a string.

**Note:** The substring is case-sensitive.

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

**Note:** If the start parameter plus the length parameter exceeds the string length, this function generates a warning (see Example 3).


Syntax

substr_count(

string,substring,start,length

)

Parameters Description
string Required. Specifies the string to check.
substring Required. Specifies the string to search for.
start Optional. Specifies where in the string to start searching.
length Optional. Specifies the length of the search.

Technical Details

Return Value: Returns the number of occurrences of the substring in the string.
PHP Version: 4+
Changelog: In PHP 5.1, the start and length parameter was added.

More examples

Example 1

Using all parameters:

"; // Using strlen() to return the string length echo substr_count($str,"is")."
"; // The number of times "is" occurs in the string echo substr_count($str,"is",2)."
"; // The string is now reduced to "is is PHP" echo substr_count($str,"is",3)."
"; // The string is now reduced to "s is PHP" echo substr_count($str,"is",3,3)."
"; // The string is now reduced to "s i" ?>

Run Example »

Example 2

Overlapping substrings:

Run Example »

Example 3

If the start and length parameters exceed the string length, this function outputs a warning:

Because the length value exceeds the string length (3 + 9 is greater than 12), this will output a warning.


PHP String Reference Manual PHP String Reference Manual