如何通过相对于输入单词的相似性对数组进行排序.

Aim*_*mOn 15 php arrays search levenshtein-distance

我有PHP数组,例如:

$arr = array("hello", "try", "hel", "hey hello");
Run Code Online (Sandbox Code Playgroud)

现在我想重新排列数组,这将基于数组和我的$ search var之间最接近的单词.

我怎样才能做到这一点?

yce*_*uto 17

使用http://php.net/manual/en/function.similar-text.php可以快速解决这个问题:

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

$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");
Run Code Online (Sandbox Code Playgroud)

或者使用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),但是仍然很贵).

$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");
Run Code Online (Sandbox Code Playgroud)


gen*_*sis 5

你可以使用levenshtein函数

<?php
// input misspelled word
$input = 'helllo';

// array of words to check against
$words  = array('hello' 'try', 'hel', 'hey hello');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // 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";
}

?>
Run Code Online (Sandbox Code Playgroud)