Compare two lines and take the difference between them as a percentage (php)

Please help compare the two lines and accept the difference between them as a percentage

I had two lines of type:

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
source share
3 answers

For this purpose, there are two interesting native functions, Similar_text () and Levenshtein ()

Example similar_text ():

 $string1 = 'AAAb'; $string2 = 'aaab'; similar_text ( $string1, $string2, $percentege ); echo $percentege . '%'; // Output: 25% 

Example levenshtein ():

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

EDIT 1

Given that the first line always has the same number of entries as the second line, you can try the code below. I created two lines for testing purposes, the second line has two equal entries and 7 different entries for a total of 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) . '%'; 
+5
source

How simple ...

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

For instance:

 $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% 
+1
source

The similarity function is highly dependent on the context in which it will be implemented. Without an explanation of what you want to do with the result of the comparison (i.e., your context), it is almost impossible to give you a similarity function from the box. Although all the similarity functions that I can think of may be valid, none of them may be suitable for your problem.

+1
source

Source: https://habr.com/ru/post/1443957/


All Articles