2014-06-30 69 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';