【问题标题】:How to sort an array by similarity in relation to an inputted word.如何通过与输入单词相关的相似性对数组进行排序。
【发布时间】:2011-11-05 06:35:12
【问题描述】:

我有关于PHP数组,例如:

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

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

我该怎么做?

【问题讨论】:

  • 您的意思是根据用户输入的输入值按特定顺序排列数组?
  • 看看soundexmetaphone。这是 PHP 中计算两个单词之间差异的两种常用方法。但我目前不知道如何根据有意义的指标对它们进行排序。你能再解释一下你的排序顺序吗?

标签: php arrays search levenshtein-distance


【解决方案1】:

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

这会计算两个字符串之间的相似度,如 Oliver 的 Programming Classics:实现世界上最好的算法 (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");

【讨论】:

  • 如何将similar_text应用于多维数组?
  • 很好的答案。如果没有输入(如完全从方程中删除)怎么办?
【解决方案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";
}

?>

【讨论】:

    【解决方案3】:

    如果要对数组进行排序,可以这样做:

    $arr = array("hello", "try", "hel", "hey hello");
    $search = "hey"; //your search var
    
    for($i=0; $i<count($arr); $i++) {
       $temp_arr[$i] = levenshtein($search, $arr[$i]);
    }
    asort($temp_arr);
    foreach($temp_arr as $k => $v) {
        $sorted_arr[] = $arr[$k];
    }
    

    $sorted_arr 应该从最接近您的搜索词的单词开始按降序排列。

    【讨论】:

      【解决方案4】:

      另一种方法是使用 similar_text 函数以百分比形式返回结果。 查看更多http://www.php.net/manual/en/function.similar-text.php

      【讨论】:

        【解决方案5】:

        虽然@yceruto 的回答正确且内容丰富,但我想扩展更多见解并展示更现代的实现语法。

        首先关于各个函数生成的分数...

        1. levenshtein()similar_text() 区分大小写,因此与 h 相比,大写的 H 与数字 6 一样不匹配。
        2. levenshtein()similar_text() 不支持多字节,因此像 ê 这样的重音字符不仅会被视为与 e 不匹配,而且可能会因为每个单独的字节不匹配而受到更重的惩罚。

        如果要进行不区分大小写的比较,只需在执行前将两个字符串都转换为大写/小写即可。

        如果您的应用程序需要多字节支持,您应该搜索提供此功能的现有存储库。

        对于那些愿意进行更深入研究的人来说,其他技术包括 metaphone()soundex(),但我不会在这个答案中深入研究这些主题。

        分数:

        Test vs "hello" |  levenshtein   |  similar_text  |   similar_text's percent   |
        ----------------+----------------+----------------+----------------------------|
        H3||0           |       5        |      0         |       0                    |
        Hallo           |       2        |      3         |      60                    |
        aloha           |       5        |      2         |      40                    |
        h               |       4        |      1         |      33.333333333333       |
        hallo           |       1        |      4         |      80                    |
        hallå           |       3        |      3         |      54.545454545455       |
        hel             |       2        |      3         |      75                    |
        helicopter      |       6        |      4         |      53.333333333333       |
        hellacious      |       5        |      5         |      66.666666666667       |
        hello           |       0        |      5         |     100                    |
        hello y'all     |       6        |      5         |      62.5                  |
        hello yall      |       5        |      5         |      66.666666666667       |
        helów           |       3        |      3         |      54.545454545455       |
        hey hello       |       4        |      5         |      71.428571428571       |
        hola            |       3        |      2         |      44.444444444444       |
        hêllo           |       2        |      4         |      72.727272727273       |
        mellow yellow   |       9        |      4         |      44.444444444444       |
        try             |       5        |      0         |       0                    |
        

        levenshtein() PHP7+ (Demo)排序

        usort($testStrings, function($a, $b) use ($needle) {
            return levenshtein($needle, $a) <=> levenshtein($needle, $b);
        });
        

        levenshtein() PHP7.4+ (Demo)排序

        usort($testStrings, fn($a, $b) => levenshtein($needle, $a) <=> levenshtein($needle, $b));
        

        **请注意,$a$b 已更改 DESC 排序的 &lt;=&gt; 评估的两侧。 请注意,hello 不能保证被定位为第一个元素

        similar_text() PHP7+ (Demo) 排序

        usort($testStrings, function($a, $b) use ($needle) {
            return similar_text($needle, $b) <=> similar_text($needle, $a);
        });
        

        similar_text() PHP7.4+ (Demo)排序

        usort($testStrings, fn($a, $b) => similar_text($needle, $b) <=> similar_text($needle, $a));
        

        注意hallåhelicopter 通过similar_text() 的返回值与similar_text() 的百分比值的差异。

        similar_text() 的 PHP7+ 百分比排序 (Demo)

        usort($testStrings, function($a, $b) use ($needle) {
            similar_text($needle, $a, $percentA);
            similar_text($needle, $b, $percentB);
            return $percentB <=> $percentA;
        });
        

        similar_text() 的百分比 PHP7.4+ (Demo) 排序

        usort($testStrings, fn($a, $b) => 
            [is_int(similar_text($needle, $b, $percentB)), $percentB]
            <=>
            [is_int(similar_text($needle, $a, $percentA)), $percentA]
        );
        

        请注意,我通过将similar_text() 的返回值转换为true,然后使用生成的percent 值来消除不需要的返回值——这允许生成百分比值而不返回很快,因为箭头函数语法不允许多行执行。


        levenshtein() 高效排序,然后只在需要抢七时调用similar_text(),PHP7+ (Demo)

        usort($testStrings, function($a, $b) use ($needle) {
            return levenshtein($needle, $a) <=> levenshtein($needle, $b)
                   ?: similar_text($needle, $b) <=> similar_text($needle, $a);
        });
        

        levenshtein() 高效排序,然后仅调用similar_text() 并在需要抢七时使用其百分比,PHP7.4+ (Demo)

        usort($testStrings, fn($a, $b) =>
            levenshtein($needle, $a) <=> levenshtein($needle, $b)
            ?: similar_text($needle, $b) <=> similar_text($needle, $a)
        );
        

        就我个人而言,除了levenshtein(),我从不在我的项目中使用任何其他东西,因为它始终如一地提供我正在寻找的结果。

        【讨论】:

          猜你喜欢
          • 2018-04-18
          • 1970-01-01
          • 2019-05-31
          • 2013-01-13
          • 2011-06-24
          • 2012-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多