Home » PHP

PHP substr_count() Function with Example

PHP substr_count() Function: Here, we are going to learn about the substr_count() Function with Example in PHP.
Submitted by IncludeHelp, on February 06, 2019

PHP substr_count() Function

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:

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

Here,

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

Examples:

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

Output

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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.