PHP - Finding number of matching words between two pieces of text?

我的未来我决定 提交于 2019-12-02 11:21:05

Easy, explode them and then use array_diff:

$totalWords = count($array_1);

$array_1 = explode(" ", $str1);
$array_2 = explode(" ", $str2);
$differenceCount = count(array_diff($array_1, $array_2));

$differentPercent = $differenceCount / ($totalWords / 100);

@Edit:

Edited code above to display percentage. However remember you may have a wrong result if the word count of array 1 and array 2 is not identical.

$arr1 = explode(" ",$str1)
$arr2 = explode(" ",$str2)

$arr3 = array_diff($arr1, $arr2);

echo(count($arr1)-count($arr3));

The way I would approach this is to explode each string and then use array_diff to compare them like this:

$arr1 = explode(' ', $str1);
$arr2 = explode(' ', $str2);
$diff = array_diff($arr1, $arr2);
echo (count($arr1) - count($diff));

That will echo out the number of similar words.

Ankur Goel
$arr1 = explode(" ",$str1)
$arr2 = explode(" ",$str2)

$arr3 = array_diff($arr1, $arr2);

i used array_intesect to check how many matches,, i used this in searching one array into other

and for preventing with auxilary verbs and prepositions(the,to,a,are etc) use -

$arr1 = str_replace(array("to", "the","a","an","in","by","but","are","is","had","have","has"),'',$arr1); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!