similar_text()

1. 定义

该函数根据Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1)算法计算两个字符串的相似度。 返回两个字符串中匹配字符的数目。

注:

  • 该实现进行了递归调用,可能会使整个进程变慢
  • 算法复杂度为O(N^3),其中N为最长字符串的长度

2. 语法

similar_text ( string $first , string $second [, float &$percent ] ) : int

3. 参数说明

参数 可选性 数据类型 描述
$first 必需 字符串 第一个比较的字符串
$second 必需 字符串 第二个比较的字符串
$percent 可选 浮点数 相似度(通过引用传递)

4. 示例

<?php

// similar_text()
// 根据`Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1)`算法计算两个字符串的相似度

$str1 = 'hello, world';
$str2 = 'hello, PHP';
$res = similar_text($str1, $str2, $percent);
var_dump($res);// 输出:int(7):相同字符的个数,这里是 hello, 
var_dump($percent);// 输出:float(63.636363636364):根据算法得出的相似度

5. 延展阅读

  • levenshtein():计算两个字符串之间的编辑距离(Levenshtein)
  • soundex():利用英文字符的读音计算近似值