Backend Development 4 min read

Using PHP substr_count() to Count Substring Occurrences

This article explains the PHP substr_count() function, its syntax, parameters, and demonstrates how to count substring occurrences with optional offset, length, and case‑sensitivity options through clear code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP substr_count() to Count Substring Occurrences

The substr_count() function in PHP calculates how many times a substring appears within a string.

Syntax :

<code>int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )</code>

Parameters:

$haystack : the string to search.

$needle : the substring to look for.

$offset (optional): starting position for the search, default 0.

$length (optional): length of the portion to search, default is the rest of the string.

The function returns the number of occurrences, or 0 if none are found.

Basic usage – counting all occurrences :

<code>$str = "Hello, World! Hello, PHP!";
$count = substr_count($str, "Hello");
echo $count; // outputs 2</code>

In this example, $str is the target string and "Hello" is the substring; the function returns 2 because "Hello" appears twice.

Using offset and length :

<code>$str = "Hello, World! Hello, PHP!";
$count = substr_count($str, "Hello", 7, 10);
echo $count; // outputs 1</code>

Here the search starts at position 7 and spans 10 characters, so only one occurrence of "Hello" is counted.

Case‑sensitive search (default) :

<code>$str = "Hello, World! hello, PHP!";
$count = substr_count($str, "hello");
echo $count; // outputs 1</code>

The function matches only substrings with the same case, therefore it finds one "hello".

Case‑insensitive search (by converting both strings to the same case):

<code>$str = "Hello, World! hello, PHP!";
$count = substr_count(strtolower($str), strtolower("hello"));
echo $count; // outputs 2</code>

Using strtolower() makes the search case‑insensitive, resulting in two matches.

Summary : The substr_count() function is a versatile tool for counting substring occurrences in PHP strings, supporting optional offset, length, and case‑sensitivity control, enabling precise string analysis in backend development.

Stringcount()offsetsubstr_countcase-sensitivelength
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.