substr_count
Counts how many times a substring occurs in a string.
Syntax
substr_count(string $haystack, string $needle): intParameters
| Parameter | Type | Description |
|---|---|---|
| $haystack | string | The string to search in. |
| $needle | string | The substring to count. |
Return value
intThe number of occurrences.
Examples
Counting words and letters:
<?php
echo substr_count('tea, coffee, tea', 'tea'), "\n";
echo substr_count('banana', 'a');Output:
2
3Overlapping occurrences are not counted:
<?php
echo substr_count('aaa', 'aa');Output:
1Notes
The search is case-sensitive. To count case-insensitively, convert both strings to the same case.
See also
- strpos — Finds the position of the first occurrence of a substring.
- str_contains — Checks whether a string contains a given substring.
Related recipes
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.