Table of Contents
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
]] )
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 ofhaystack
.
<?php $str = 'abc.phpmypassion.com';
echo strlen($str); // 21echo substr_count($str, '.'); //// the string is reduced to 'phpmyps', so it prints 1echo substr_count($str, '.', 4);//the text is reduced to 'phpm',so it prints 0echo substr_count($str, '.', 4, 4);// generates a warning because 10+12 > 21echo substr_count($str, '.', 10, 12);// prints only 3, because it doesn't count overlapped substrings$str2= 'phpmypassion.com'; echo substr_count($str2, 'p');?>
needle
substring occurs in thehaystack
string. Please note thatneedle
is case sensitive.