検索文字列を正規表現に変換することでパターンを一致させることができます。次に、その正規表現を使って検索し、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;
}
この質問はすでにここに答えた:私は、1つのまたは2つの単語を検索したいのでhttp://stackoverflow.com/questions/29781719/method-for-comparing-strings-in-php – rak007
鉱山は、異なっています本の中で、そして単語が少し間違って綴られることを可能にする。その質問はまっすぐなレベンションの距離です。私の例でlevenshtein距離を使用した場合、 "and orange"は返されません。文字列に "orangis"が含まれているか、または文字列が1文字間違っているかどうかを確認する必要があります。文字列が大きくなるにつれて、私はlevenshtein距離を増やすでしょう。 –
あなたは$ find変数を同様の正規表現に変換し、すべての一致を使ってlevensthein比較を使用する必要があります。かなり簡単なテキストであれば。関数が返すもの、単一のマッチ、またはすべてのマッチを返しますか? –