PHP Levenshtein Closest Match
Ever have a need to find the closest word match? Say you have a word and need to get the closest match of it against a list of other words. Your original word may or may not be in the list?
Then you need Levenshtein... Levenshtein. calculates the closest match by the lowest number of operations (insert, replace or delete) it takes to get from one string to another.
I took the example from the PHP dot net site and wrapped it up in a little function.
-
//CALCULATE CLOSEST MATCH USING LEVENSHTEIN FUNCTION
-
function closest($seed, $haystack){
-
$shortest = -1;
-
foreach ($haystack as $word){
-
if ($lev == 0) {
-
$closest = $word; $shortest = 0; break;
-
}
-
if ($lev <= $shortest || $shortest <0) {
-
$closest = $word; $shortest = $lev;
-
}
-
}
-
return $closest;
-
}
Here is an example of its use:
-
$words = array('Master of Arts in Forensic Psychology','Bachelor of Arts in Psychology','Master of Business Administration', 'Doctor of Business Administration', 'Doctor of Education in Educational Leadership', 'Doctor of Psychology in Clinical Psychology');
-
-
-
//RETURNS: Master of Arts in Forensic Psychology
You’re currently reading “ PHP Levenshtein Closest Match ,” an entry on BRADINO
- Published:
- 3.24.07 / 3pm
- Category:
- PHP














Have your say