5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mb_levenshtein 二つの文字列のレーベンシュタイン距離を計算する(マルチバイト対応版)

Last updated at Posted at 2012-12-26
この関数は文字数制約のある雑な実装になっています。制約のない実装は@mpywさんの [マルチバイト対応] レーベンシュタイン距離を求めるをご覧ください。

levenshtein()のマルチバイト対応版

<?php

function mb_levenshtein($string1, $string2)
{
	$tokens1 = preg_split('/(?<!^)(?!$)/u', $string1);
	$tokens2 = preg_split('/(?<!^)(?!$)/u', $string2);
	$tokens = array_unique(array_merge($tokens1, $tokens2));

	if ( count($tokens) > 26 )
	{
		return false;
	}

	$ascii = 'a';

	foreach ( $tokens as $token )
	{
		$string1 = str_replace($token, $ascii, $string1);
		$string2 = str_replace($token, $ascii, $string2);
		$ascii ++;
	}

	$arguments = func_get_args();
	$arguments[0] = $string1;
	$arguments[1] = $string2;

	return call_user_func_array('levenshtein', $arguments);
}

var_dump(mb_levenshtein('あとうかい', 'かとうあい')); // int(2)

5
5
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?