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 :

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

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 :

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

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 :

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

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

Case‑sensitive search (default) :

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

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):

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

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

String_countOFFSETsubstr_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

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.