PHP Reference ยท String Functions
PHP substr_count() function
Reference for PHP substr_count(): count non-overlapping occurrences of a substring, offset and length arguments, case sensitivity and counting words.
substr_count() returns how many times a substring appears in a string. Occurrences are counted without overlap: after a match, the search resumes after the end of that match.
The search is case-sensitive. You can restrict the search to a part of the string with the optional $offset and $length arguments.
<?php echo substr_count("banana", "an"); // 2 echo substr_count("aaaa", "aa"); // 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int
| Name | Description |
|---|---|
$haystack |
The string to search in. |
$needle |
The substring to count. It must not be empty. |
$offset |
Where to start. Negative counts from the end. |
$length |
Maximum length of the part to search, from the offset. Negative leaves that many bytes off the end. null means to the end. |
Return value: the number of non-overlapping occurrences, as an int.
Errors: a ValueError is thrown if $needle is empty, or if $offset or $length are outside the string.
Usage notes
- No overlaps.
substr_count("aaa", "aa")is1. For overlapping counts, loop withstrpos()and advance by one. - Case-sensitive. Normalize case with
strtolower()first for case-insensitive counting. - Single character counts. For counting every character at once, use
count_chars(); for words usestr_word_count(). - Bytes. Offsets and lengths are in bytes. The count itself is safe on UTF-8 text when the needle is valid UTF-8; use
mb_substr_count()for the mbstring-aware version. - Not a regex. Use
preg_match_all()for patterns. - Fast. It scans once without building new strings, so it is better than
count(explode(...)) - 1.
Related
strpos(),str_word_count(),str_replace()(its fourth argument also counts),explode()- Lessons: Strings, String functions