note 107114 modified in function.levenshtein by danbrown

From: Date: Mon, 09 Jan 2012 18:28:27 +0000
Subject: note 107114 modified in function.levenshtein by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185481@lists.php.net to get a copy of this message
I really like [the manual's] example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity: <?php function wordMatch($words, $input, $sensitivity){ $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; } } if($shortest <= $sensitivity){ return $closest; } else { return 0; } } $word = 'PINEEEEAPPLE'; $words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato'); echo wordMatch($words, strtolower($word), 2); ?> --was-- I really like your example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity: function wordMatch($words, $input, $sensitivity){ $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; } } if($shortest <= $sensitivity){ return $closest; } else { return 0; } } $word = 'PINEEEEAPPLE'; $words = array('apple','pineapple','banana','orange', 'radish','carrot','pea','bean','potato'); echo wordMatch($words, strtolower($word), 2); http://php.net/manual/en/function.levenshtein.php

« previous php.notes (#185481) next »