Latest web development tutorials

PHP substr_count () function

PHP String Reference PHP String Reference

Examples

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

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

Running instance »

substr_count () function calculates the number of occurrences in the string substring.

Note: substring is case-sensitive.

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

NOTE: If you start the argument plus length parameter is greater than the length of the string, the function will generate a warning (see Example 3).


grammar

substr_count( string,substring,start,length )

参数 描述
string 必需。规定要检查的字符串。
substring 必需。规定要检索的字符串。
start 可选。规定在字符串中何处开始搜索。
length 可选。规定搜索的长度。

technical details

return value: Returns the number of occurrences in the string substring.
PHP version: 4+
Update log: In PHP 5.1, add the start and length parameters.


More examples

Example 1

Use 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"
?>

Running instance »

Example 2

Overlapping substring:

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

Running instance »

Example 3

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

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

Due to the length of the value exceeds the length of the string (3 + 9 greater than 12). So it will output a warning.



PHP String Reference PHP String Reference