dtek dtek - 5 months ago 42
PHP Question

PHP String Comparison and similarity index

What's an elegant code for finding common alphabets among two strings without including the space in PHP?

Also return a similarity index i.e. count the number of common characters and return that as a percentage over the total number of characters.

Suppose i have one string "LEGENDARY ", whereas other as "BARNEY STINSON" so i need to find common letters b/w both without including space.

Also my code should return a similarity index i.e. count the number of common characters and return that as a percentage over the total number of characters.

For these two strings, the common characters are "ARNEY" so the score is 5/22 ~= 22%. Any help on this?

Answer

see similar_text(). And if you want to exclude spaces simple str_replace(' ', '', $string); prior.

echo similar_text ( 'LEGENDARY' , 'BARNEYSTINSON', $percent); // outputs 3
echo $percent; // outputs 27.272727272727

Here's another way using only unique characters

<?php
function unique_chars($string) {
   return count_chars(strtolower(str_replace(' ', '', $string)), 3);
}
function compare_strings($a, $b) {
    $index = similar_text(unique_chars($a), unique_chars($b), $percent);
    return array('index' => $index, 'percent' => $percent);
}
print_r( compare_strings('LEGENDARY', 'BARNEY STINSON') );

// outputs:
?>

Array
(
    [index] => 5
    [percent] => 55.555555555556
)