PHP 原生的similar_text()函数、levenshtein()函数对中文汉字支持不好,我自己写了一个,测试使用正常,推荐给大家,如果有什么问题,请留言
similar_text()中文汉字版
代码如下:
//拆分字符串
function split_str($str) {
preg_match_all("/./u", $str, $arr);
return $arr[0];
}
//相似度检测
function similar_text_cn($str1, $str2) {
$arr_1 = array_unique(split_str($str1));
$arr_2 = array_unique(split_str($str2));
$similarity = count($arr_2) - count(array_diff($arr_2, $arr_1));
return $similarity;
}
levenshtein()中文汉字版
代码如下:
//拆分字符串
function mbStringToArray($string, $encoding = 'UTF-8') {
$arrayResult = array();
while ($iLen = mb_strlen($string, $encoding)) {
array_push($arrayResult, mb_substr($string, 0, 1, $encoding));
$string = mb_substr($string, 1, $iLen, $encoding);
}
return $arrayResult;
}
//编辑距离
function levenshtein_cn($str1, $str2, $costReplace = 1, $encoding = 'UTF-8') {
$count_same_letter = 0;
$d = array();
$mb_len1 = mb_strlen($str1, $encoding);
$mb_len2 = mb_strlen($str2, $encoding);
$mb_str1 = mbStringToArray($str1, $encoding);
$mb_str2 = mbStringToArray($str2, $encoding);
for ($i1 &#61; 0; $i1 <&#61; $mb_len1; $i1&#43;&#43;) {
$d[$i1] &#61; array();
$d[$i1][0] &#61; $i1;
}
for ($i2 &#61; 0; $i2 <&#61; $mb_len2; $i2&#43;&#43;) {
$d[0][$i2] &#61; $i2;
}
for ($i1 &#61; 1; $i1 <&#61; $mb_len1; $i1&#43;&#43;) {
for ($i2 &#61; 1; $i2 <&#61; $mb_len2; $i2&#43;&#43;) {
// $cost &#61; ($str1[$i1 - 1] &#61;&#61; $str2[$i2 - 1]) ? 0 : 1;
if ($mb_str1[$i1 - 1] &#61;&#61;&#61; $mb_str2[$i2 - 1]) {
$cost &#61; 0;
$count_same_letter&#43;&#43;;
} else {
$cost &#61; $costReplace; //替换
}
$d[$i1][$i2] &#61; min($d[$i1 - 1][$i2] &#43; 1, //插入
$d[$i1][$i2 - 1] &#43; 1, //删除
$d[$i1 - 1][$i2 - 1] &#43; $cost);
}
}
return $d[$mb_len1][$mb_len2];
//return array(&#39;distance&#39; &#61;> $d[$mb_len1][$mb_len2], &#39;count_same_letter&#39; &#61;> $count_same_letter);
}
最长公共子序列LCS()
代码如下:
本文原创发布php中文网&#xff0c;转载请注明出处&#xff0c;感谢您的尊重&#xff01;