PHP Tutorial - PHP substr_count() Function






Definition

The substr_count() function counts the occurrence of a substring. The substr_count() function is case-sensitive.

Syntax

PHP substr_count() Function has the following syntax.

substr_count(string,substring,start,length)

Parameter

ParameterIs RequiredDescription
stringRequired.String to check
substringRequired.String to search for
startOptional.Where in string to start searching
lengthOptional.Length of the search




Return

PHP substr_count() Function returns the the number of times the substring occurs in the string.

Example 1

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


<?php
echo substr_count("Hello world. The world is nice","world");
echo "\n";
$myString = "I say, PHP, PHP, and PHP!"; 
echo substr_count( $myString, "PHP" );

?>

The code above generates the following result.





Example 2

Using all parameters:


<?php
$str = "This is from java2s.com. Yes it is.";
echo strlen($str)."\n";                 // Using strlen() to return the string length
echo substr_count($str,"is")."\n";      // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."\n";  
echo substr_count($str,"is",3)."\n"; 
echo substr_count($str,"is",3,3)."\n"; 
?>

The code above generates the following result.

Example 3

Overlapped substrings:


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

The code above generates the following result.

Example 4

If the start and length parameters exceeds the string length, substr_count will output a warning:


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

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

The code above generates the following result.