如何根据与输入单词的相似度对数组进行排序. [英] How to sort an array by similarity in relation to an inputted word.

查看:35
本文介绍了如何根据与输入单词的相似度对数组进行排序.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于 PHP 数组,例如:

I have on PHP array, for example:

$arr = array("hello", "try", "hel", "hey hello");

现在我想根据数组和 $search var 之间最接近的单词重新排列数组.

Now I want to do rearrange of the array which will be based on the most nearly close words between the array and my $search var.

我该怎么做?

推荐答案

这是一个使用 http://php.net/manual/en/function.similar-text.php:

这会计算两个字符串之间的相似度,如编程经典:Oliver 的《实现世界上最好的算法》(ISBN 0-131-00413-1)中所述.请注意,此实现不像 Oliver 的伪代码那样使用堆栈,而是使用递归调用,这可能会或可能不会加速整个过程.另请注意,该算法的复杂度为 O(N**3),其中 N 是最长字符串的长度.

This calculates the similarity between two strings as described in Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

$userInput = 'Bradley123';

$list = array('Bob', 'Brad', 'Britney');

usort($list, function ($a, $b) use ($userInput) {
    similar_text($userInput, $a, $percentA);
    similar_text($userInput, $b, $percentB);

    return $percentA === $percentB ? 0 : ($percentA > $percentB ? -1 : 1);
});

var_dump($list); //output: array("Brad", "Britney", "Bob");

<小时>

或者使用 http://php.net/manual/en/function.levenshtein.php:

Levenshtein 距离定义为将 str1 转换为 str2 时必须替换、插入或删除的最少字符数.该算法的复杂度为O(m*n),其中n和m分别为str1和str2的长度(与similar_text()相比相当不错,为O(max(n,m)**3),但还是贵).

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

$userInput = 'Bradley123';

$list = array('Bob', 'Brad', 'Britney');

usort($list, function ($a, $b) use ($userInput) {
    $levA = levenshtein($userInput, $a);
    $levB = levenshtein($userInput, $b);

    return $levA === $levB ? 0 : ($levA > $levB ? 1 : -1);
});

var_dump($list); //output: array("Britney", "Brad", "Bob");

这篇关于如何根据与输入单词的相似度对数组进行排序.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆