PHP substr_count() Function with Example

By IncludeHelp Last updated : December 27, 2023

PHP substr_count() Function

The substr_count() function is a string function in PHP, it is used to find the total number of occurrences of a substring in the given string.

Syntax

The syntax of the substr_count() function:

substr_count(string, substring, [offset], [length]);

Parameters

The parameters of the substr_count() function:

  • string is the main string in which we have to perform the search for the substring.
  • substring is the part of the string that we have search in the string.
  • offset is an optional parameter, it defines the start index – from where you want to search the string. Its default value is 0.
  • length is also an optional parameter, it defines length of the search i.e. search operation will start from offset and finishes with offset+length position.

Return Value

The return value of this method is string, it returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive. [Source]

Sample Input/Output

Input: 
str = "Hello friends how are your friends?";
substring = "friends";
Output:
2

Input:
str = "Hello friends how are your friends?";
substring = "Hello";
Output:
1

Input:
str = "Hello friends how are your friends?";
substring = "Hi";
Output:
0

Example of PHP substr_count() Function

<?php
$str = "Hello friends how are your friends?";
$substring = "friends";
$count = 0; //variable to store occurrences of the substrig

//search will be performed in complete string
$count = substr_count($str, $substring);
echo ("$substring found $count times.\n");

//search will be performed in complete string
$substring = "Hi";
$count = substr_count($str, $substring);
echo ("$substring found $count times.\n");

//search will be performed from 14th index
$substring = "friends";
$count = substr_count($str, $substring, 14);
echo ("$substring found $count times.\n");	

//search will be performed from 14th index to next 10 chars
$substring = "friends";
$count = substr_count($str, $substring, 14, 10);
echo ("$substring found $count times.\n");		
?>

Output

The output of the above example is:

friends found 2 times.
Hi found 0 times.
friends found 1 times.
friends found 0 times.

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.