Backend Development 3 min read

PHP substr_count() Function: Usage, Parameters, and Examples

This article explains the PHP substr_count() function, detailing its syntax, parameter meanings, return value, and provides multiple code examples demonstrating how to count substring occurrences with optional offset and length arguments.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP substr_count() Function: Usage, Parameters, and Examples

The substr_count() function in PHP returns the number of times a substring ( needle ) appears in a larger string ( haystack ), with case‑sensitivity.

Signature:

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

Parameters:

haystack : The string to search within.

needle : The substring to count.

offset (optional): The position in haystack where counting starts.

length (optional): The maximum length to search after the offset; if the sum of offset and length exceeds the length of haystack , a warning is issued.

Return value: An integer representing the count of needle occurrences.

Examples:

haystack length
echo substr_count($text, 'is', 5, 10); // warning, result 1 (non‑overlapping)

$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd'); // 1 (does not count overlapping)
?>

The examples illustrate basic counting, the effect of offset and length parameters, and the fact that overlapping substrings are not counted.

backendProgrammingphpstring-functionssubstr_count
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.