3

重複の可能性:
PHPでの文字列の類似性:長い文字列のレーベンシュタインのような関数

件名があります

$subj = "Director, My Company";

比較する複数の文字列のリスト:

$str1 = "Foo bar";
$str2 = "Lorem Ipsum";
$str3 = "Director";

ここで達成したいのは、に関連する最も近い文字列を見つけること$subjです。それは可能ですか?

4

2 に答える 2

22

関数はlevenshtein()あなたが期待することをします。Levenshteinアルゴリズムは、ある文字列を別の文字列に変換するために必要な挿入および置換アクションの数を計算します。結果はと呼ばれますedit distance。距離は、要求に応じて文字列を比較するために使用できます。

この例は、PHPlevenshtein()関数のドキュメントから派生しています。

<?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?

幸運を!

于 2013-01-20T03:08:54.360 に答える
2

http://php.net/manual/en/function.levenshtein.phpを使用して、2つの文字列間の距離を決定できます。

$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);
于 2013-01-20T03:04:40.430 に答える