| | 449 | * PHP implementation of Levenshtein edit distance algorithm. |
| | 450 | * Uses the native PHP implementation when possible for speed. |
| | 451 | * The native levenshtein is limited to 255 bytes. |
| | 452 | * |
| | 453 | * @since 4.5.0 |
| | 454 | * |
| | 455 | * @param string $str1 |
| | 456 | * @param string $str2 |
| | 457 | * @param int $length1 |
| | 458 | * @param int $length2 |
| | 459 | * @return int |
| | 460 | */ |
| | 461 | public function levenshtein( $str1, $str2, $length1, $length2 ) { |
| | 462 | if ( $length1 == 0 ) { |
| | 463 | return $length2; |
| | 464 | } |
| | 465 | if ( $length2 == 0 ) { |
| | 466 | return $length1; |
| | 467 | } |
| | 468 | if ( $str1 === $str2 ) { |
| | 469 | return 0; |
| | 470 | } |
| | 471 | |
| | 472 | $bytelength1 = strlen( $str1 ); |
| | 473 | $bytelength2 = strlen( $str2 ); |
| | 474 | if ( $bytelength1 === $length1 && $bytelength1 <= 255 |
| | 475 | && $bytelength2 === $length2 && $bytelength2 <= 255 |
| | 476 | ) { |
| | 477 | return levenshtein( $str1, $str2 ); |
| | 478 | } |
| | 479 | |
| | 480 | $prevRow = range( 0, $length2 ); |
| | 481 | for ( $i = 0; $i < $length1; $i++ ) { |
| | 482 | $currentRow = array(); |
| | 483 | $currentRow[0] = $i + 1; |
| | 484 | $c1 = mb_substr( $str1, $i, 1 ); |
| | 485 | for ( $j = 0; $j < $length2; $j++ ) { |
| | 486 | $c2 = mb_substr( $str2, $j, 1 ); |
| | 487 | $insertions = $prevRow[$j + 1] + 1; |
| | 488 | $deletions = $currentRow[$j] + 1; |
| | 489 | $substitutions = $prevRow[$j] + ( ( $c1 != $c2 ) ? 1 : 0 ); |
| | 490 | $currentRow[] = min( $insertions, $deletions, $substitutions ); |
| | 491 | } |
| | 492 | $prevRow = $currentRow; |
| | 493 | } |
| | 494 | |
| | 495 | return $prevRow[$length2]; |
| | 496 | } |
| | 497 | |
| | 498 | /** |