levenshtein - 두 문자열 사이의 Levenshtein 거리를 계산합니다. 정보
PHP levenshtein - 두 문자열 사이의 Levenshtein 거리를 계산합니다.본문
levenshtein - 두 문자열 사이의 Levenshtein 거리를 계산합니다.
설명 ¶
int levenshtein ( string $str1 , string $str2 )
int levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del )
Levenshtein distance는 변환하기 위해 바꾸거나 삽입하거나 삭제해야하는 최소 문자 수로 정의 str1됩니다 str2. 알고리즘의 복잡성은 O (m * n)입니다 . 여기서 n 과 m 은 O (max (n, m) ** 3) 인 similar_text () 의 길이 str1와 str2(오히려 좋지만 여전히 비쌉니다. ).
가장 간단한 형식에서 함수는 매개 변수로 두 개의 문자열 만 가져오고 str1변환에 필요한 삽입, 교체 및 삭제 작업의 수만 계산합니다 str2.
두 번째 변형은 삽입, 교체 및 삭제 작업의 비용을 정의하는 세 개의 추가 매개 변수를 취합니다. 이는 변형 1보다 일반적이며 적응력이 있지만 효율적이지는 않습니다.
매개 변수 ¶
str1
Levenshtein 거리에 대해 평가되는 문자열 중 하나입니다.
str2
Levenshtein 거리에 대해 평가되는 문자열 중 하나입니다.
cost_ins
삽입 비용을 정의합니다.
cost_rep
대체 비용을 정의합니다.
cost_del
삭제 비용을 정의합니다.
반환 값 ¶
이 함수는 두 인수 문자열 사이의 Levenshtein-Distance 또는 인수 문자열 중 하나가 255 자의 제한보다 긴 경우 -1을 반환합니다.
예 ¶
Example # 1 levenshtein () 예제
<?php
// input misspelled word
$input = 'carrrot';
// array of words to check against
$words = array('apple','pineapple','banana','orange',
'radish','carrot','pea','bean','potato');
// no shortest distance found, yet
$shortest = -1;
// loop through words to find the closest
foreach ($words as $word) {
// calculate the distance between the input word,
// and the current word
$lev = levenshtein($input, $word);
// check for an exact match
if ($lev == 0) {
// closest word is this one (exact match)
$closest = $word;
$shortest = 0;
// break out of the loop; we've found an exact match
break;
}
// if this distance is less than the next found shortest
// distance, OR if a next shortest word has not yet been found
if ($lev <= $shortest || $shortest < 0) {
// set the closest match, and shortest distance
$closest = $word;
$shortest = $lev;
}
}
echo "Input word: $input\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}
?>
위의 예제는 다음과 같이 출력됩니다 :
입력 단어 : carrrot
당신은 의미 했나요? 당근?
0
댓글 0개