Bob Dylan
Bob Dylan

Reputation: 91

compare the two strings and take the difference between them in percent (php)

Help please to compare two strings and take the difference between them in percent

I had two strings like:

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;

Upvotes: 4

Views: 563

Answers (3)

raina77ow
raina77ow

Reputation: 106375

How about as simple as...

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

For example:

$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%

Upvotes: 1

Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

The similarity function depends strongly on the context in which will be implemented. Without an explanation of what you want to do with the result of the comparison (i.e. your context) it's almost impossible to give you a similarity function out of the box. Although all of the similarity functions I can think of could be valid, none of them could be suited for your problem.

Upvotes: 1

Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

There are two interesting native functions for this purpose, similar_text() and levenshtein()

Example of similar_text():

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

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

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

Example of levenshtein():

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

EDIT 1

Considering that the first string always have the same quantity of entries that second string, you can try the below code. I've created two strings for test purpose, second string has two equal entries and 7 different entries in 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) . '%';

Upvotes: 5

Related Questions