chillywilly
chillywilly

Reputation: 424

PHP count instances of array items in a string

In PHP 7.3:

Given this array of low relevancy keywords...

$low_relevancy_keys = array('guitar','bass');

and these possible strings...

$keywords_db = "red white"; // desired result 0
$keywords_db = "red bass"; // desired result 1
$keywords_db = "red guitar"; // desired result 1
$keywords_db = "bass guitar"; // desired result 2

I need to know the number of matches as described above. A tedious way is to convert the string to a new array ($keywords_db_array), loop through $keywords_db_array, and then loop through $low_relevancy_keys while incrementing a count of matches. Is there a more direct method in PHP?

Upvotes: 0

Views: 49

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

The way you described in your question but using array_* functions:

echo count(array_intersect(explode(' ', $keywords_db), $low_relevancy_keys)); 

(note that you can replace explode with preg_split if you need to be more flexible)

or using preg_match_all (that returns the number of matches):

$pattern = '~\b' . implode('\b|\b', $low_relevancy_keys) . '\b~';

echo preg_match_all($pattern, $keywords_db); 

demo

Upvotes: 2

Related Questions