I am trying to find closest match from an array. For this I use levenshtein()
, but levenshtein()
returns only first matched string or first closest match.
Here is my scenario:
$words = array('Break Noise','Engine Noise','Vehicle is jerking');
If my input is Noise
, I want to get both Break Noise
and Engine Noise
.
Is it possible to do?
levenshtein()
returns me only Break Noise
which is the first element.
After getting two upvotes, I'm sucked into leaving this answer on the screen.
$input="Noise";
$words = array('Break Noise','Engine Noise','Noises','Vehicle is jerking','Nose','noise');
$filtered=array_filter($words,function($v)use($input){return stripos($v,$input)!==false;});
usort($filtered,function($a,$b)use($input) {
return levenshtein($input,$a)>levenshtein($input,$b)?1:-1;
});
var_export($filtered);
Output:
array (
0 => 'Noises',
1 => 'noise',
2 => 'Break Noise',
3 => 'Engine Noise',
)
This will first filter out "Noise-less" elements, then sort your array using levenshtein()
.