如何按与输入单词相关的相似性对数组进行排序。

2022-08-30 22:03:09

我有PHP数组,例如:

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

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

我该怎么做?


答案 1

这是一个使用 http://php.net/manual/en/function.similar-text.php 的快速解决方案:

这计算了两个字符串之间的相似性,如编程经典:奥利弗的实现世界最佳算法(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");

或使用 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");

答案 2

您可以使用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";
}

?>