如何在PHP中preg匹配levenshtein距离的字符串

时间:2016-09-16 15:32:12

标签: php preg-match levenshtein-distance

我如何preg匹配一个字符串,但是容忍模式中的变量levensthein距离?

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

这将返回'和橙子&#39 ;;

1 个答案:

答案 0 :(得分:2)

通过将搜索字符串转换为正则表达式,我们可以匹配模式。然后我们使用该正则表达式进行搜索并与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;
}