PHP 最接近字符串比较 [英] PHP nearest string comparison

查看:26
本文介绍了PHP 最接近字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有我的主题字符串

$subj = "董事,我的公司";

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

and a list of multiple strings to be compared:

$str1 = "Foo bar";
$str2 = "Lorem Ipsum";
$str3 = "导演";

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

What I want to achieve here is to find the nearest string related to $subj. Is it possible to do it?

推荐答案

levenshtein() 函数将满足您的期望.Levenshtein 算法计算将某个字符串转换为另一个字符串所需的插入和替换操作的数量.结果称为编辑距离.距离可用于根据您的要求比较字符串.

The levenshtein() function will do what you expect. The Levenshtein algorithm calculates the number of insert and replace actions being required to transform some string into another. The result is called an edit distance. The distance can be used to compare strings as you requested.

此示例源自 PHP levenshtein() 函数.

This example is derived from the documentation of the PHP levenshtein() function.

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

祝你好运!

这篇关于PHP 最接近字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆