函数签名
similar_text(string $str1, string $str2, float &$percent = null): int
- 返回匹配字符数 (整数)
- 第三个参数引用返回相似百分比 (浮点数)
- 算法基于最长公共子序列变体,非 Levenshtein 距离
基础示例
<?php
$target = 'stupid';
$words = [
'stupid', 'stu and pid', 'hello', 'foobar',
'stpid', 'upid', 'stuuupid', 'sstuuupiiid',
];
foreach ($words as $word) {
similar_text($word, $target, $percent);
printf("%-15s : %3d chars matched, %.1f%%\n", $word, $percent);
}
/* 输出:
stupid : 100 chars matched, 100.0%
stu and pid : 71 chars matched, 71.4%
hello : 0 chars matched, 0.0%
foobar : 0 chars matched, 0.0%
stpid : 91 chars matched, 90.9%
upid : 80 chars matched, 80.0%
stuuupid : 86 chars matched, 85.7%
sstuuupiiid : 71 chars matched, 71.4%
*/
核心特性
| 特性 | similar_text() | levenshtein() |
| 返回值 | 匹配字符数 + 百分比 | 编辑距离 (插入/删除/替换次数) |
| 对称性 | 是 | 是 |
| 大小写敏感 | 是 | 是 |
| 长度限制 | 无 | 255 字符 |
| 性能 | O(n³) 较慢 | O(n*m) 较快 |
| 适用场景 | 相似度百分比展示、阈值过滤 | 拼写纠错、差异高亮、排序 |
实战应用:模糊搜索建议
<?php
function suggestSimilar(string $input, array $dictionary, float $threshold = 70): array {
$results = [];
foreach ($dictionary as $word) {
similar_text($input, $word, $pct);
if ($pct >= $threshold) {
$results[$word] = $pct;
}
}
arsort($results);
return array_keys($results);
}
$dict = ['apple', 'application', 'apply', 'banana', 'orange', 'app'];
print_r(suggestSimilar('aple', $dict, 60));
// Array ( [0] => apple [1] => apply [2] => application )
实战应用:去重合并相似标题
<?php
function mergeSimilarTitles(array $titles, float $threshold = 85): array {
$groups = [];
$used = [];
foreach ($titles as $i => $title) {
if (isset($used[$i])) continue;
$group = [$title];
$used[$i] = true;
foreach ($titles as $j => $other) {
if ($i === $j || isset($used[$j])) continue;
similar_text($title, $other, $pct);
if ($pct >= $threshold) {
$group[] = $other;
$used[$j] = true;
}
}
$groups[] = $group;
}
return $groups;
}
$titles = [
'PHP 8.2 新特性详解',
'PHP 8.2 新特性完全指南',
'PHP 8.1 新特性回顾',
'Laravel 10 发布',
'Laravel 10 正式版发布了',
];
print_r(mergeSimilarTitles($titles, 80));
/* 输出:
Array
(
[0] => Array ( [0] => PHP 8.2 新特性详解 [1] => PHP 8.2 新特性完全指南 )
[1] => Array ( [0] => PHP 8.1 新特性回顾 )
[2] => Array ( [0] => Laravel 10 发布 [1] => Laravel 10 正式版发布了 )
)
*/
性能优化建议
- 大词典 (>1万) 先用
levenshtein() 快速筛选候选,再用 similar_text() 精确计算百分比
- 建立倒排索引或 BK-Tree 结构加速近似查找
- 仅对用户输入的关键词计算,避免全量对比
- PHP 8.1+ 可用
str_contains() 等新函数预过滤
局限性
🔴 不处理语义相似 (如“苹果” vs “水果”)
🔴 对中文分词无感知,按字符比较
🔴 长文本对比极慢,建议先摘要/分词
🔴 百分比计算基于 (2*匹配字符数)/(长度1+长度2),非标准 Jaccard/余弦相似度
结合 levenshtein()、metaphone() (英文发音编码) 可构建更强大的模糊匹配系统。
copyright ©
萬盛學電腦網 all rights reserved