duanhuhong5255 2017-06-07 06:47 采纳率: 0%
浏览 197
已采纳

如何从数组中获取所有最接近的匹配字符串?

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.

  • 写回答

1条回答 默认 最新

  • drtzb06222 2017-06-07 07:02
    关注

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?