Master PHP’s substr_count(): Count Substring Occurrences Easily

Learn how to use PHP’s substr_count() function to count the occurrences of a substring within a string, including its syntax, parameter details, and a practical example that demonstrates counting “Hello” in a sample text, plus tips for more complex applications.

php Courses
php Courses
php Courses
Master PHP’s substr_count(): Count Substring Occurrences Easily

In PHP, the substr_count() function is used to count how many times a substring appears within a string, which is especially handy for statistical text analysis.

substr_count() function syntax

int substr_count ( string $string , string $substring [, int $start = 0 [, int $length ]] )
$string

: the string to be examined; $sub: the substring to look for; $start: the position to start checking, default 0; $length: the length to check, default the whole string.

Below is a concrete example demonstrating how to use substr_count() to count the occurrences of a substring in a string.

<?php

// Count occurrences of a substring in a string
$string = "Hello world, Hello PHP, Hello substr_count!";
$sub = "Hello";
$count = substr_count($string, $sub);

// Output the result
echo "The substring \"{$sub}\" appears {$count} times.";
?>

The example assigns the target string to $string and the substring to $sub, then calls substr_count() to compute the count, storing it in $count. The echo statement prints the number of occurrences, which in this case is 3.

The substr_count() function can also be applied in more complex scenarios, such as counting keyword occurrences in user‑entered text within a text editor.

Overall, substr_count() provides a concise way to obtain substring occurrence counts, simplifying many string‑related statistical tasks in PHP.

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.

Code ExampleString Manipulationsubstr_count
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.