Tuesday, January 24, 2017

anil

How to count the number of substring occurrences in a string ?


Common PHP issue that mostly developer face. below is the solution for such type of issue..


substr_count

substr_count  Count the number of substring occurrences

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
Note:
This function doesn't count overlapped substrings. See the example below!

Parameters 

haystack
The string to search in
needle
The substring to search for
offset
The offset where to start counting. If the offset is negative, counting starts from the end of the string.
length
The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length. A negative length counts from the end of haystack.

Return Values 

This function returns an integer.
source: php.net
<?php $str 'abc.phpmypassion.com';
echo strlen($str); // 21echo substr_count($str'.'); //
// the string is reduced to 'phpmyps', so it prints 1
echo substr_count($str'.'4);//the text is reduced to 'phpm',so it prints 0
echo substr_count($str'.'44);// generates a warning because 10+12 > 21
echo substr_count($str'.'1012);// prints only 3, because it doesn't count overlapped substrings
$str2'phpmypassion.com'; echo substr_count($str2'p');?>

Check Video :- 

 



About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about web programming. Here you will find a huge information on web development, web design, PHP, Python, Digital Marketing and Latest technology.

Subscribe to this Blog via Email :

Note: Only a member of this blog may post a comment.