While playing with PHP, I have found a fact that we can determine how many times a string occurs inside another string quite easily by using PCRE. In fact, we can use preg_match_all() to match a string (instead of a complex pattern) to another string and get the matches as an array. Then we count() the array’s first key to know how many times the string has been found in the other one.
We feed preg_match_all() a solid string as a pattern as the first parameter. And it’d do the job for us.
Here’s the code snippet:
1 2 3 4 5 6 7 8 9 10 |
<?php $string = "my name is masnun. i am Masnun. my website is maSnun.com"; preg_match_all("/masnun/i",$string,$m); print_r($m); echo "\n"; echo count($m[0])." occurrences found \n\n"; ?> |
In the above example, we add an “i” modifier for case insensitive matching. If you want it to be a case sensitive matching, just ignore the “i” modifier.
Results:
1 2 3 4 5 6 7 8 9 10 11 12 |
Array ( [0] => Array ( [0] => masnun [1] => Masnun [2] => maSnun ) ) 3 occurrences found |
Additionally this method can be used instead of strpos() when we try to find if a string exists in another.