计算单词串中匹配单词的百分比


Calculate percentage of matching words in a string of words

我有一个字符串,其中包含来自数据库的一堆带有空格分隔符的单词,以及另一个类似的字符串,其中包含来自用户输入的单词。

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

如何查看与数据库关键字匹配的用户关键字百分比?

所以在上面的例子中,它将是60%。

我知道我必须知道总共有多少个单词,然后检查db关键字字符串中包含多少个匹配的用户关键字,然后像3 / 5 * 100一样得到百分比(对于上面的例子)。

您可以使用array_intersect函数来计算这个百分比:

$usrKeywords = 'test1 test4 test2'; //$_POST['keywords']
$dbKeywords  = 'test1 test2 test3 test4 test5'; //from the DB
$arr1 = explode(' ', $usrKeywords);
$arr2 = explode(' ', $dbKeywords);
$aint = array_intersect($arr2, $arr1);
print_r($aint);
echo "percentage = " . (count($aint) * 100 / count($arr2)); // 60
$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';