如何在PHP中使用levenshtein距离预匹配字符串

如何在PHP中使用levenshtein距离预匹配字符串,php,preg-match,levenshtein-distance,Php,Preg Match,Levenshtein Distance,如何预匹配字符串,但在模式的距离内允许变量levens $string = 'i eat apples and oranges all day long'; $find = 'and orangis'; $distance = 1; $matches = pregMatch_withLevensthein($find, $distance, $string); 这将返回“和橘子” 通过将搜索字符串转换为regexp,我们可以匹配模式。然后,我们使用该regexp进行搜索,并与levenshte

如何预匹配字符串,但在模式的距离内允许变量levens

$string = 'i eat apples and oranges all day long';
$find = 'and orangis';
$distance = 1;
$matches = pregMatch_withLevensthein($find, $distance, $string);

这将返回“和橘子”

通过将搜索字符串转换为regexp,我们可以匹配模式。然后,我们使用该regexp进行搜索,并与levenshtein进行比较。如果它与边界匹配,我们可以返回值

$string = 'i eat apples and oranges all day long';
$find = 'and orangis';
$distance = 1;
$matches = preg_match_levensthein($find, $distance, $string);
var_dump($matches);

function preg_match_levensthein($find, $distance, $string)
{
    $found = array();

    // Covert find into regex
    $parts = explode(' ', $find);
    $regexes = array();
    foreach ($parts as $part) {
        $regexes[] = '[a-z0-9]{' . strlen($part) . '}';
    }
    $regexp = '#' . implode('\s', $regexes) . '#i';

    // Find all matches
    preg_match_all($regexp, $string, $matches);

    foreach ($matches as $match) {
        // Check levenshtein distance and add to the found if within bounds
        if (levenshtein($match[0], $find) <= $distance) {
            $found[] = $match[0];
        }
    }

    // return found
    return $found;
}
$string='我整天吃苹果和桔子';
$find='and orangis';
$distance=1;
$matches=preg\u match\u levenstein($find,$distance,$string);
var_dump($matches);
函数preg\u match\u levenstein($find,$distance,$string)
{
$found=array();
//秘密发现正则表达式
$parts=爆炸(“”,$find);
$regexes=array();
foreach($parts作为$part){
$regexes[]='[a-z0-9]{.strlen($part.');
}
$regexp='#'。内爆('\s',$regexes)。'#i';
//查找所有匹配项
preg_match_all($regexp,$string,$matches);
foreach($matches作为$match进行匹配){
//检查levenshtein距离,如果在范围内,则添加到查找到的距离

如果(levenshtein($match[0],$find)这个问题已经在这里得到了回答:我的问题不同,因为我想在一本书中找到一两个单词,并允许这些单词拼写稍有错误。这个问题是直接向上的levenshtein距离。如果我在我的示例中使用levenshtein距离,它不会返回“and oranges”.我需要检查字符串是否包含“and orangis”或者一个相同但有1个字符错误的字符串。随着字符串变大,我会增加levenshtein距离。您需要将$find变量转换为类似的正则表达式,然后在所有匹配项中使用levenshtein比较。如果它只是文本,应该很容易实现。您希望函数返回什么,single匹配还是所有匹配?Chappell,找到相似的模式是我迷路的地方。似乎唯一的方法是从一个字符转到下一个字符,然后在下一个X字符上使用Levensthein,直到找到0或1距离的匹配。这确实回答了问题,所以我接受它。谢谢Chappell。不幸的是简单地说,它对“andranges”之类的内容不起作用(如果您将内爆更改为
(\s?
)之类的内容,它会找到零或一个空格字符)。