2016-09-16 9 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); 

これは 'andangang'を返します。

+0

この質問はすでにここに答えた:私は、1つのまたは2つの単語を検索したいのでhttp://stackoverflow.com/questions/29781719/method-for-comparing-strings-in-php – rak007

+0

鉱山は、異なっています本の中で、そして単語が少し間違って綴られることを可能にする。その質問はまっすぐなレベンションの距離です。私の例でlevenshtein距離を使用した場合、 "and orange"は返されません。文字列に "orangis"が含まれているか、または文字列が1文字間違っているかどうかを確認する必要があります。文字列が大きくなるにつれて、私はlevenshtein距離を増やすでしょう。 –

+0

あなたは$ find変数を同様の正規表現に変換し、すべての一致を使ってlevensthein比較を使用する必要があります。かなり簡単なテキストであれば。関数が返すもの、単一のマッチ、またはすべてのマッチを返しますか? –

答えて

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; 
} 
+0

これは実際に質問に答えるので、私はそれを受け入れています。チャペルに感謝します。残念ながら、 "andoranges"のようなものではうまくいきません:( –

+0

implodeを '(\ s?)'のように変更すると、0または1つの空白文字が見つかります。 –

関連する問題