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.
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.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.