PHP最近的字符串比较

kag*_*gat 1 php similarity string-comparison

可能重复:
PHP中的字符串相似性:levenshtein类似于长字符串的函数

我有我的主题字符串

$subj = "Director, My Company";

以及要比较的多个字符串的列表:

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

我想在这里实现的是找到与之相关的最近的字符串$subj.有可能吗?

hek*_*mgl 16

levenshtein()功能将满足您的期望.leventstein算法计算所需的插入和替换动作的数量,以将某些字符串转换为另一个字符串.leventhstein的结果被称为edit distance.距离可用于比较您请求的字符串.

此示例源自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";
}
Run Code Online (Sandbox Code Playgroud)

脚本输出是

Input word: Director, My Company
Did you mean: Director?
Run Code Online (Sandbox Code Playgroud)

祝好运!