2014-06-30 68 views
2

我有一串字符串,其中有一个空格分隔符来自我的数据库,另一个字符串来自用户输入。计算字符串中匹配字的百分比

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

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

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

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

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

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

回答

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

什么偷偷摸摸的解决方案中使用数组在此交汇。大! – thpl

+1

+1,可爱的答案。 – zx81

+0

谢谢@ zx81很高兴你喜欢它。 – anubhava

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';