note 106381 added to function.levenshtein
| From: | ChaimChaikin at osu1 dot php dot net | Date: | Wed, 02 Nov 2011 19:40:20 +0000 |
| Subject: | note 106381 added to function.levenshtein | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-184277@lists.php.net to get a copy of this message | ||
As regards to Example #1 above, would it not be more efficient to first use a simple php ==
comparison to check if the strings are equal even before testing the word with levenshtein().
Something like this:
<?php
// input misspelled word
$input = 'carrrot';
// array of words to check against
$words = array('apple','pineapple','banana','orange',
'radish','carrot','pea','bean','potato');
// no shortest distance found, yet
$shortest = -1;
// loop through words to find the closest
foreach ($words as $word) {
// check for an exact match
if ($input == $word) {
// closest word is this one (exact match)
$closest = $word;
$shortest = 0;
// break out of the loop; we've found an exact match
break;
}
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($input, $word);
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
echo "Input word: $input\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
?>
----
Server IP: 192.41.42.26
Probable Submitter: 196.215.27.219
----
Manual Page -- http://www.php.net/manual/en/function.levenshtein.php
Edit -- https://master.php.net/note/edit/106381
Del: integrated -- https://master.php.net/note/delete/106381/integrated
Del: useless -- https://master.php.net/note/delete/106381/useless
Del: bad code -- https://master.php.net/note/delete/106381/bad+code
Del: spam -- https://master.php.net/note/delete/106381/spam
Del: non-english -- https://master.php.net/note/delete/106381/non-english
Del: in docs -- https://master.php.net/note/delete/106381/in+docs
Del: other reasons-- https://master.php.net/note/delete/106381
Reject -- https://master.php.net/note/reject/106381
Search -- https://master.php.net/manage/user-notes.php