2016-09-16 3 views
1

문자열을 preg 처리 할 수 ​​있지만 어떻게 패턴에서 변수 levensthein 거리를 허용 할 수 있습니까?PHP에서 문자열을 levenshtein 거리와 일치시키는 방법

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

'and and oranges';

+0

이 질문은 이미 여기에 대답했다 : http://stackoverflow.com/questions/29781719/method-for-comparing-strings-in-php – rak007

+0

나는 하나 개 또는 두 개의 단어를 찾을 원하기 때문에 광산은 다르다 책에서, 그리고 약간 철자가 틀린 낱말을 허용하십시오. 그 질문은 똑바로 올라가는 거리다. 필자가 예제에서 levenshtein distance를 사용했다면 "and 오렌지"를 반환하지 않을 것이다. 문자열에 "orangis"가 포함되어 있는지 확인하거나 문자열에 1 문자 이상 잘못 입력했는지 확인해야합니다. 문자열이 커지면 levenshtein 거리가 늘어납니다. –

+0

$ find 변수를 비슷한 정규식으로 변환 한 다음 모든 일치 항목을 사용하면 levensthein 비교를 사용해야합니다. 그것이 꽤 쉬운 텍스트 일뿐입니다. 함수가 반환 할 대상, 일치하는 항목 하나 또는 모든 일치 항목을 원 하시겠습니까? –

답변

2

검색 문자열을 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; 
} 
+0

이것은 실제로 질문에 대답하므로 받아 들일 것입니다. Chappell에게 감사드립니다. 불행히도, "andoranges"와 같은 것은 작동하지 않을 것입니다 : ( –

+0

implode를'(\ s?)'와 같이 0 또는 하나의 공백 문자로 변경하면됩니다. –

관련 문제