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:

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

echo substr_count($text, 'is'); // 2

// Using offset
echo substr_count($text, 'is', 3); // 0 (search starts after "is")

// Using offset and length
echo substr_count($text, 'is', 3, 3); // 0

// Demonstrating warning when offset+length > 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.

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.

BackendprogrammingPHPsubstr_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.