Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

substr_count

Counts how many times a substring occurs in a string.

Syntax

substr_count(string $haystack, string $needle): int

Parameters

ParameterTypeDescription
$haystackstringThe string to search in.
$needlestringThe 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
3

Overlapping occurrences are not counted:

<?php
 
echo substr_count('aaa', 'aa');

Output:

1

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.