447 | | |
| 437 | |
| 438 | /** |
| 439 | * Customized Levenshtein Distance that can accept more than 255 characters |
| 440 | * http://php.net/manual/en/function.levenshtein.php#85387 |
| 441 | * @param string $s1 |
| 442 | * @param string $s2 |
| 443 | * @return int |
| 444 | */ |
| 445 | public function levenshtein( $s1, $s2 ) { |
| 446 | $sleft = ( strlen( $s1 ) > strlen( $s2 )) ? $s1 : $s2; |
| 447 | $sright = ( strlen( $s1 ) > strlen( $s2 )) ? $s2 : $s1; |
| 448 | $nleftlength = strlen( $sleft ); |
| 449 | $nrightlength = strlen( $sright ); |
| 450 | if ( 0 == $nleftlength ) { |
| 451 | return $nrightlength; |
| 452 | } elseif ( 0 == $nrightlength ) { |
| 453 | return $nleftlength; |
| 454 | } elseif ( $sleft === $sright ) { |
| 455 | return 0; |
| 456 | } elseif ( ( $nleftlength < $nrightlength ) && ( strpos( $sright, $sleft ) !== FALSE) ) { |
| 457 | return $nrightlength - $nleftlength; |
| 458 | } elseif ( ( $nrightlength < $nleftlength ) && ( strpos( $sleft, $sright ) !== FALSE) ) { |
| 459 | return $nleftlength - $nrightlength; |
| 460 | } else { |
| 461 | $nsdistance = range( 1, $nrightlength + 1 ); |
| 462 | for ( $nleftpos = 1; $nleftpos <= $nleftlength; ++$nleftpos ) { |
| 463 | $cleft = $sleft[ $nleftpos - 1 ]; |
| 464 | $ndiagonal = $nleftpos - 1; |
| 465 | $nsdistance[0] = $nleftpos; |
| 466 | for ( $nrightpos = 1; $nrightpos <= $nrightlength; ++$nrightpos ) { |
| 467 | $cright = $sright[ $nrightpos - 1 ]; |
| 468 | $ncost = ( $cright == $cleft ) ? 0 : 1; |
| 469 | $nnewdiagonal = $nsdistance[ $nrightpos ]; |
| 470 | $nsdistance[ $nrightpos ] = |
| 471 | min($nsdistance[ $nrightpos ] + 1, |
| 472 | $nsdistance[ $nrightpos - 1 ] + 1, |
| 473 | $ndiagonal + $ncost); |
| 474 | $ndiagonal = $nnewdiagonal; |
| 475 | } |
| 476 | } |
| 477 | return $nsdistance[ $nrightlength ]; |
| 478 | } |
| 479 | } |