Main Content

How similar are two words

Archive - Originally posted on "The Horse's Mouth" - 2006-03-11 06:26:58 - Graham Ellis

Do you want to help your web site user find what he's looking for on your web site, even if he mis-spells a name or word in a search? PHP provides you with three facilities - soundex, metaphones and Levenshtein distance calculations - which let you compare two words and see how similar they are when written (levenshtein) or spoken (metaphone, soundex).

I've put a demonstration up for you to try - it's here - using metaphones and levenshtein - here's the "engine" at the heart of the code:

$ident = levenshtein($first,$second);
$meta1 = metaphone($first);
$meta2 = metaphone($second);
if ($ident) {
print "Words are $ident levenshtein steps out<br>";
if ($meta1 == $meta2) {
print "But they sound the same (metaphone $meta1)\n";
} else {
$id = levenshtein($meta1,$meta2);
print "They sound different too - metaphones ";
print "$meta1 and $meta2 are $id steps out\n";
}
} else {
print "Words are identical\n";
}


The complete source code is available too if you want to get in deep.

Having learnt how to see if two words are similar, you'll want to know how to make lots of comparisons against a single word when you're writing a search algorithm. That's another day's story perhaps, but it's something that we do as a matter of routine by keeping a database table of metaphones ....