2015-01-08 147 views
1

目前我正在試圖找出有多少話在兩個字符串的百分比匹配PHP - 文本匹配

的想法是,你對陣另外一個字符串,並得到他們是多麼類似於%。

我目前有什麼是一個粗略的想法,並想知道我是否可以得到一些幫助 的想法是將每個字符串轉換爲數組,你可以逐個遍歷列表並添加1到$匹配if有一個匹配和0如果不存在

<?php> 
$originalText = "The quick brown fox jumps over the lazy dog"; 
$comparisonText = "The quick red fox leaps over the sleeping dog"; 
//to get a count the number of words we are trying to match 
$strNum = str_word_count($originalText); 

$arroriginalText = explode(" ", $originalText); 
$arrcomparisonText = explode(" ", $comparisonText); 

//THIS IS WHERE I'M STUCK 
//creating some form of a loop to go through the array of strings 

if (preg_match("*word from $arroriginalText*, *word from $arrcomparisonText*", $matches)) { 
//not fully understanding what to put here 
} 

//i'm bad at maths 
$strNum - $matches = $percentageFind 
$percentageFind/$strNum = $decimal 
$decimal * 100 = $theAnswer 
?> 

我不知道如果我已經做出了我想清楚,但任何幫助將不勝感激。

+1

你能不能用['array_diff'(http://php.net/manual/en/function.array-diff.php)? – naththedeveloper

+3

那麼,你可以使用第三個參數或['similar_text()'](http://php.net/similar_text),除非你真的想自己實現....'similar_text($ originalText,$ comparisonText ,$ PERC); var_dump($ perc);' – Wrikken

+0

Wrikken我對PHP語言顯然不夠了解,你提出的方法很簡單,它讓我的腦袋一直受到傷害,一直在浪費我試圖實現我自己的方法 – InitForTheLongRun

回答

0
$matches = 0; 

if(empty($arroriginalText)) { 
    echo 'Empty'; 
    die(); 
} 

for($n = 0; $n < count($arroriginalText); $n++) { 
    if($arrcomparisonText[$n] === $arroriginalText[$n]) { 
    $matches++; 
    } 
} 

$percentage = 100 * $matches/count($arroriginalText); 

或更好,但(未經測試)

$percentage = count(array_diff($arroriginalText, $arrcomparisonText))/count($arroriginalText); 
+0

謝謝你,新的PHP和我不理解的語法 – InitForTheLongRun