- mb_strlen: documentation ( source)
- min: documentation ( source)
<?php
function LevenshteinDistance($str1, $str2) {
$d = array ();
$len1 = mb_strlen($str1,"UTF-8");
$len2 = mb_strlen($str2,"UTF-8");
echo $len1.$len2;
for ($i1 = 0; $i1 <= $len1; $i1++) {
$d[$i1] = array ();
$d[$i1][0] = $i1;
}
for ($i2 = 0; $i2 <= $len2; $i2++) {
$d[0][$i2] = $i2;
}
for ($i1 = 1; $i1 <= $len1; $i1++) {
for ($i2 = 1; $i2 <= $len2; $i2++) {
$cost = ($str1[$i1 - 1] == $str2[$i2 - 1]) ? 0 : 1;
$d[$i1][$i2] = min(
$d[$i1 - 1][$i2 ] + 1, //挿入
$d[$i1 ][$i2 - 1] + 1, //削除
$d[$i1 - 1][$i2 - 1] + $cost //置換
);
}
}
return $d[$len1][$len2];
}
echo LevenshteinDistance("こんにちは","こんにち");
?>