similar_text(string $string1, string $string2, float &$percent = null): int
計算兩字串相似度,回傳匹配字元數。可選第三參數以參考方式回傳百分比相似度 (0-100)。精確度優於 levenshtein(),但效能較慢。
| 參數 | 必要性 | 說明 |
|---|---|---|
string1 | 必需 | 第一個比較字串 |
string2 | 必需 | 第二個比較字串 |
percent | 可選 | 參考變數,儲存百分比相似度 |
匹配字元數 (int)。
<?php
similar_text("Hello World", "Hello Shanghai", $percent);
echo $percent . "%"; // 輸出: 66.666666666667%
// 封裝為可複用函數
function similarityPercentage($a, $b): float {
similar_text($a, $b, $p);
return round($p, 2);
}
echo similarityPercentage("apple", "apples"); // 83.33
echo similarityPercentage("apple", "orange"); // 22.22
?>
| 項目 | similar_text() | levenshtein() |
|---|---|---|
| 回傳 | 匹配字元數 + 百分比 | 編輯距離 |
| 速度 | 較慢 | 較快 |
| 精確度 | 較高 | 標準 |
| 適用 | 短字串、需百分比 | 長字串、拼寫檢查 |