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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int

Parameters

ParameterDescription
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

Count matchesTry it yourself
<?php
echo substr_count("hello world, hello PHP", "hello"), "\n";
echo substr_count("a,b,,c", ","), "\n";

Output

2
3
Overlaps and counting linesTry it yourself
<?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

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?