0

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?

2
  • There is no more direct method in PHP. Commented Mar 29, 2020 at 21:18
  • BTW I don't call it tedious. Commented Mar 29, 2020 at 21:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

array_intersect is exactly what I was looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.