HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

PHP substr_count() Function

PHP String Reference PHP String Reference

Example

Count the number of times "world" occurs 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 occurs in a string.

Note: The substring is case-sensitive.

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

Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see example 3).


Syntax

substr_count(string,substring,start,length)

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

Technical Details

Return Value: Returns the  the number of times the substring occurs in the string
PHP Version: 4+
Changelog: The start and length parameters were added in PHP 5.1


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

Overlapped 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 exceeds the string length, this function will output a warning:

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

This will output a warning because the length value exceeds the string length (3+9 is greater than 12)



PHP String Reference PHP String Reference

Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE