Categories
PHP

PHP: Counting Occurrences with PCRE

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:

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:

Additionally this method can be used instead of strpos() when we try to find if a string exists in another.