我目前正在尝试找到两个字符串匹配的字数的百分比
这个想法是你将一个字符串与另一个字符串匹配,得到它们有多相似的百分比。
我现在所拥有的是一个粗略的想法,并想知道我是否能得到一些帮助 我们的想法是将每个字符串转换为一个数组,您可以逐个遍历列表,如果匹配则添加1到$匹配,如果没有匹配则添加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
?>
我不确定我是否已经做出了我想清楚的事情,但是我会非常感激任何帮助。
答案 0 :(得分: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 );