note 81046 added to function.levenshtein

From: Date: Tue, 12 Feb 2008 16:52:41 +0000
Subject: note 81046 added to function.levenshtein
Groups: php.notes 
Request: Send a blank email to php-notes+get-136068@lists.php.net to get a copy of this message
Using PHP's example along with Patrick's comparison percentage function, I have come up with a function that returns the closest word from an array, and assigns the percentage to a referenced variable: <?php function closest_word($input, $words, &$percent = null) { $shortest = -1; foreach ($words as $word) { $lev = levenshtein($input, $word); if ($lev == 0) { $closest = $word; $shortest = 0; break; } if ($lev <= $shortest || $shortest < 0) { $closest = $word; $shortest = $lev; } } $percent = 1 - levenshtein($input, $closest) / max(strlen($input), strlen($closest)); return $closest; } ?> Usage: <?php $input = 'carrrot'; $words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato'); $percent = null; $found = closest_word($input, $words, $percent); printf('Closest word to "%s": %s (%s%% match)', $input, $found, round($percent * 100, 2)); ?> I found that lowercasing the array prior to comparing yields a better comparison when the case is not of importance, for example: comparing a user-inputted category to a list of existing categories. I also found that when the percentage was above 75%, it was usually the match that I was looking for. ---- Server IP: 66.207.199.35 Probable Submitter: 209.29.21.251 ---- Manual Page -- http://www.php.net/manual/en/function.levenshtein.php Edit -- https://master.php.net/note/edit/81046 Del: integrated -- https://master.php.net/note/delete/81046/integrated Del: useless -- https://master.php.net/note/delete/81046/useless Del: bad code -- https://master.php.net/note/delete/81046/bad+code Del: spam -- https://master.php.net/note/delete/81046/spam Del: non-english -- https://master.php.net/note/delete/81046/non-english Del: in docs -- https://master.php.net/note/delete/81046/in+docs Del: other reasons-- https://master.php.net/note/delete/81046 Reject -- https://master.php.net/note/reject/81046 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#136068) next »