similar_text() 是 PHP 內建但較少被使用的函數,專門用於計算兩個字串的相似程度,返回相似字元數,並可選擇性返回相似百分比。
int similar_text(string $first, string $second, float &$percent = null)
$first:第一個字串$second:第二個字串$percent:引用參數,若提供將儲存相似百分比(0-100)$percent,會計算:相似字元數 * 200 / (strlen($first) + strlen($second))<?php
$str1 = "PHP 是最好的語言";
$str2 = "PHP 是最棒的語言";
$similar = similar_text($str1, $str2, $percent);
echo "字串1:$str1\n";
echo "字串2:$str2\n";
echo "相似字元數:$similar\n";
echo "相似百分比:$percent%\n";
/* 輸出範例:
字串1:PHP 是最好的語言
字串2:PHP 是最棒的語言
相似字元數:9
相似百分比:81.818181818182%
*/
?>
| 特性 | similar_text() | levenshtein() |
|---|---|---|
| 演算法基礎 | 最長公共子序列 (LCS) | 編輯距離 |
| 速度 | 較慢(O(N³)) | 極快(O(N×M)) |
| 精確度 | 語義相似度較直觀 | 編輯操作次數 |
| 適用場景 | 短字串、語義比對 | 長字串、拼寫檢查、DNA序列 |
| 中文支援 | 按字元比較,支援 UTF-8 | 按位元組,需配合 mbstring |
<?php
$str1 = str_repeat("測試字串", 100); // 約 1200 字元
$str2 = str_repeat("測試字串", 99) . "不同";
$start = microtime(true);
similar_text($str1, $str2, $p1);
echo "similar_text: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
$dist = levenshtein($str1, $str2);
echo "levenshtein: " . (microtime(true) - $start) . "s\n";
/* 典型輸出:
similar_text: 0.125s
levenshtein: 0.002s
*/
?>
<?php
function find_similar($keyword, $candidates, $threshold = 60) {
$results = [];
foreach ($candidates as $candidate) {
similar_text($keyword, $candidate, $percent);
if ($percent >= $threshold) {
$results[$candidate] = $percent;
}
}
arsort($results); // 按相似度降序排序
return $results;
}
// 使用範例
$keywords = ["PHP教程", "PHP入門", "Python教程", "Java教程", "PHO教程"];
$input = "PHP教程";
$matches = find_similar($input, $keywords, 50);
print_r($matches);
/* 輸出:
Array
(
[PHP教程] => 100
[PHP入門] => 66.666666666667
[PHO教程] => 83.333333333333
[Python教程] => 50
)
*/
?>
similar_text() 在 PHP 7+ 可正確處理 UTF-8 中文字元(視為單字元)similar_text() 是 PHP 中語義相似度計算的利器,雖然速度不如 levenshtein(),但對於短字串(如標題、標籤、關鍵字)的模糊匹配、去重、推薦場景,其結果更符合人類直覺。搭配閾值過濾,可快速構建「猜你想搜」、「相關標籤」等功能。