Strings levenshtein
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
levenshtein — 두 문자열 사이의 Levenshtein 거리 계산
설명
levenshtein( string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1 ): int
Levenshtein 거리는 string1
을 string2
로 변환하기 위해 교체, 삽입 또는 삭제해야 하는 최소 문자 수로 정의됩니다. 알고리즘의 복잡성은 O(m*n)
입니다. 여기서 n
과 m
은 string1
과 string2
의 길이입니다(O(max(n,m)**3)
인 similar_text()와 비교할 때 다소 우수함). 그러나 여전히 비싸다).
insertion_cost
, replacement_cost
및/또는 deletion_cost
이 1
과 같지 않으면 알고리즘이 가장 저렴한 변환을 선택하도록 조정됩니다. 예를 들어 $insertion_cost + $deletion_cost < $replacement_cost
인 경우 교체가 수행되지 않고 대신 삽입 및 삭제가 수행됩니다.
매개변수
string1
- Levenshtein 거리에 대해 평가되는 문자열 중 하나입니다.
string2
- Levenshtein 거리에 대해 평가되는 문자열 중 하나입니다.
insertion_cost
- 삽입 비용을 정의합니다.
replacement_cost
- 교체 비용을 정의합니다.
deletion_cost
- 삭제 비용을 정의합니다.
반환 값
이 함수는 두 인수 문자열 사이의 Levenshtein-Distance를 반환하거나 인수 문자열 중 하나가 255자 제한보다 긴 경우 -1을 반환합니다.
변경 로그
버전 | 설명 |
---|---|
8.0.0 | 이 버전 이전에는 levenshtein()을 두 개 또는 다섯 개의 인수로 호출해야 했습니다. |
Examples
예제 #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";
}
?>
위의 예는 다음을 출력합니다.
Input word: carrrot Did you mean: carrot?
기타
- soundex() - Calculate the soundex key of a string
- similar_text() - Calculate the similarity between two strings
- metaphone() - Calculate the metaphone key of a string