PHP substr_count() Function with Example

PHP substr_count() Function: Here, we will find out about the substr_count() Function with Example in PHP.

PHP substr_count() Function

substr_count() work is a string capacity in PHP, it is utilized to locate the complete number of events of a substring in the given string.

Syntax:

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

Here,

  • the string is the primary string where we need to play out the quest for the substring.
  • substring is the piece of the string that we have a search in the string.
  • balance is a discretionary parameter, it characterizes the beginning list – from where you need to look through the string. Its default value is 0.
  • length is likewise a discretionary parameter, it characterizes length of the inquiry for example search activity will begin from counterbalance and completes with offset+length position.

Example:

    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

PHP Code:

<?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");		
?>

Leave a Comment

error: Alert: Content is protected!!