4

请帮助比较两个字符串并以百分比表示它们之间的差异

我有两个字符串,例如:

first string:
253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,253.0.0.0,247.0.0.24,197.0.0.35,189.0.0.98....
second string:
255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127,255.255.255.127....

$first_array = explode(",", $out_string);
$second_array = explode(",", $out_string_1);
$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));

$result = implode(",",$result_array);
echo $result;
4

3 回答 3

5

为此目的,有两个有趣的本机函数,similar_text()levenshtein()

similar_text() 示例:

$string1 = 'AAAb';
$string2 = 'aaab';

similar_text ( $string1, $string2, $percentege );

echo $percentege . '%'; // Output: 25%

levenshtein() 示例:

levenshtein($string1, $string2, 1, 1000, 1000000);

编辑 1

考虑到第一个字符串总是与第二个字符串具有相同数量的条目,您可以尝试以下代码。我为测试目的创建了两个字符串,第二个字符串有两个相等的条目和 7 个不同的条目,总共 9 个。

$first_string = '253.0.0.1,253.0.0.2,253.0.0.3,253.0.0.4,253.0.0.5,253.0.0.6,253.0.0.7,253.0.0.8,253.0.0.9';

$second_string = '253.0.0.1,253.0.0.2,255.255.255.127,255.255.255.128,255.255.255.129,255.255.255.130,255.255.255.131,255.255.255.132,255.255.255.133';

$first_array = explode(',', $first_string);

$second_array = explode(',', $second_string);

$total_entries = count($first_array);

$array_differences = array_diff($first_array, $second_array);

$different_entries = count($array_differences);

$percentage = ( $different_entries / $total_entries ) * 100 ;

echo 'Difference: ' . round($percentage, 2) . '%';
于 2012-11-04T15:04:45.383 回答
1

怎么这么简单...

$difference = count($result_array) / count($first_array) * 100;

例如:

$arr1 = array(1, 2, 3, 4);
$arr2 = array(5, 2, 4, 8);
$res  = array_diff($arr1, $arr2); 
printf("%.02f%%", count($res) / count($arr1) * 100);    # 50.00%
于 2012-11-04T15:00:05.167 回答
1

相似度函数很大程度上取决于将要实现的上下文。如果没有解释你想对比较结果做什么(即你的上下文),几乎不可能给你一个开箱即用的相似性函数。尽管我能想到的所有相似函数都可能有效,但它们都不适合您的问题。

于 2012-11-04T16:07:36.603 回答