PHP substr_count() Function
Topic: PHP String ReferencePrev|Next
Description
The substr_count()
function counts the number of times a substring occurs in a string.
Please note that the substring search is performed in a case-sensitive manner.
The following table summarizes the technical details of this function.
Return Value: | Returns the number of times the substring occurs in the string. |
---|---|
Changelog: | Since PHP 7.1.0, the start and length parameters may now be a negative number. The length parameter may also be 0 now. |
Version: | PHP 4+ |
Syntax
The basic syntax of the substr_count()
function is given with:
The following example shows the substr_count()
function in action.
Example
Run this code »<?php
// Sample strings
$str = "The woodpeckers live in the woods.";
$substr = "wood";
// Counting substring occurrences
echo substr_count($str, $substr);
?>
Parameters
The substr_count()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to search in. |
substring | Required. Specifies the substring to search for. |
start | Optional. Specifies the position in the string from where the counting will start. If it is negative, counting will start from the end of the string. |
length | Optional. Specifies the maximum length (after the specified start) to search for the substring. A negative length counts from the end of string. |
More Examples
Here're some more examples showing how substr_count()
function actually works:
The following example demonstrates the usage of different parameters.
Example
Run this code »<?php
// Sample strings
$str = "The woodpeckers live in the woods.";
$substr = "wood";
// Getting the original length of the string
echo strlen($str)."<br>"; // Prints: 34
// The string is reduced to 'woodpeckers', so it prints 1
echo substr_count($str, $substr, 4, 11)."<br>";
// The string is reduced to 'the wood', so it prints 1
echo substr_count($str, $substr, -10, 9)."<br>";
// The string is reduced to 'live in', so it prints 0
echo substr_count($str, $substr, 16, 7);
?>
This function does not count overlapped substrings as you can see in the following example.
Example
Run this code »<?php
// Sample strings
$str = "abcabcabc";
$substr = "abcabc";
// Counting substring occurrences
echo substr_count($str, $substr); // Prints: 1 (not 2)
?>
If the sum of the start and the length parameter values is greater than the length of the string, this function generates a warning. Let's take a look at the following example:
Example
Run this code »<?php
// Sample strings
$str = "The woodpeckers live in the woods.";
$substr = "wood";
// Generates a warning because 10 + 30 > 34
echo substr_count($str, $substr, 10, 30);
?>