PHP 8 reference · String Functions
PHP substr_count() Function
Count how many times a substring occurs in a string. Matches don't overlap, and the search is case-sensitive.
PHP 8 Since 4.0
Syntax
substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int
Parameters
| Parameter | Description |
|---|---|
haystack |
The string to search in. |
needle |
The substring to count. |
offset optional |
Where to start counting. Default: 0 |
length optional |
How many bytes to search. |
Return value
The number of matches.
Examples
<?php
echo substr_count("hello world, hello PHP", "hello"), "\n";
echo substr_count("a,b,,c", ","), "\n";
Output
2 3
<?php
echo substr_count("aaaa", "aa"), "\n"; // not overlapping
echo substr_count("Line 1\nLine 2\nLine 3", "\n") + 1, "\n";
Output
2 3
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
str.count()· Python
Related
str_word_count()· Count the words in a string, or return them as an array. Words are runs of letters plus ' and -; digits split words.strpos()· Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false.- PHP Strings · tutorial