PHP substr_count()Functions

PHP String 参考手册PHP String Reference Manual

Examples

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

<?php
echo substr_count("Hello world. The world is nice","world");
?>

Run example »

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

Note:The substring is case-sensitive.

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

Note:If the start parameter plus the length parameter is greater than the string length, 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 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 times the substring appears in the string.
PHP Version: 4+
Changelog: In PHP 5.1, thestartandlengthparameters were added.


More Examples

Example 1

Using all parameters:

<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo 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 is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>

Run example »

Example 2

Overlapping substrings:

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

Run example »

Example 3

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

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

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



PHP String 参考手册PHP String Reference Manual Other Extensions