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

The PHP substr_count() function counts the number of non‑overlapping occurrences of a substring within a string, optionally starting from a given offset and limiting the search length, and the article explains its signature, parameters, return value, and provides practical code examples.

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

substr_count() is a PHP built‑in function that returns the number of times a substring (needle) occurs in a string (haystack), with optional offset and length parameters.

Signature:

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

Parameters:

haystack – the string to search in.

needle – the substring to count.

offset – the position in $haystack where counting starts (default 0).

length – the maximum length to search after the offset; if offset+length exceeds the haystack length, a warning is issued.

Return value: The function returns an integer representing the count of non‑overlapping occurrences of $needle.

Examples:

<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2

echo substr_count($text, 'is', 3); // 0

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

Note that substr_count() is case‑sensitive and does not count overlapping substrings.

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.

Backendphp-functionsstring-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

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.