php - Calculate percentage of matching words in a string of words

764

I have a string with a bunch of words with a space delimiter that comes from my database and another similar string with words from user input.

$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']

$dbKeywords  = 'test1 test2 test3 test4 test5'; //from the DB

How can I check the percentage of how many user keywords match the database keywords?

So for the above case it would be 60%.

I know I would have to know how many words there are in total, and then check how many matching user keywords are contained in the db keywords string and then do like3 / 5 * 100 to get the percentage (for the above example).

But code wise I have no idea how to do this.

35

Answer

Solution:

$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']
$dbKeywords  = 'test1 test2 test3 test4 test5';

$user_keywords_unique = array_unique(explode(' ', $usrKeywords));
$db_keywords_unique = array_unique(explode(' ', $dbKeywords));
$matches = array_intersect($user_keywords_unique, $db_keywords_unique);
$percentage = 100*count($matches)/count($user_keywords_unique);
echo $percentage.'% of the user keywords exist in the database';

People are also looking for solutions to the problem: php - woocommerce - checkout fails/doesn't work

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.