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

时间:2014-06-30 08:43:57

标签: php regex string percentage

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

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

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

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

因此,对于上述情况,这将是60%。

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

但代码明智我不知道如何做到这一点。

2 个答案:

答案 0 :(得分:6)

您可以使用array_intersect function来计算此百分比:

$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

答案 1 :(得分:0)

$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';
相关问题