PHP最近字符串比较

4

2
请定义“nearest”。 - hakre
4
你可以尝试使用http://php.net/manual/en/function.levenshtein.php。 - Viacheslav Kondratiuk
@Kagat-Kagat:你说的“nearest”是什么意思? - Luka
嗨,在我的例子中,最接近的字符串将是 $str3,它是最接近 $subj 的字符串。 - kagat-kagat
1
搞定了,我不知道 levenshtein()。谢谢! - kagat-kagat
2个回答

24

levenshtein() 函数会按您的期望进行操作。Levenshtein算法计算将某个字符串转换为另一个字符串所需的插入和替换操作数,结果被称为 编辑距离。该距离可用于比较字符串,如您所要求的。

这个例子来自PHP levenshtein()函数的文档。

<?php

$input = 'Director, My Company';

// array of words to check against
$words  = array('Foo bar','Lorem Ispum','Director');

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

脚本输出是

Input word: Director, My Company
Did you mean: Director?

祝你好运!


2

您可以使用http://php.net/manual/en/function.levenshtein.php函数来计算两个字符串之间的距离。

$subj = "Director, My Company";
$str = array();
$str[] = "Foo bar";
$str[] = "Lorem Ipsum";
$str[] = "Director";

$minStr = "";
$minDis = PHP_INT_MAX;
for ($str as $curStr) {
  $dis = levenshtein($subj, $curStr);
  if ($dis < $minDis) {
    $minDis = $dis;
    $minStr = $curStr;
  }
}
echo($minStr);

这更像是一条评论而不是答案。请先参考重复/类似的问题。 - hakre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接