如何在 MySQL 和 PHP 中有效率地計算編輯距離?

Barbara Streisand
發布: 2024-11-14 17:57:02
原創
506 人瀏覽過

How to Calculate Levenshtein Distance Efficiently in MySQL and PHP?

Levenshtein Distance Calculation in MySQL and PHP

The Levenshtein distance is a popular metric for measuring the similarity between two strings. It finds applications in a variety of scenarios, particularly in spell checking and search engines. This article explores how to compute the Levenshtein distance between a given term and all terms in a MySQL database using PHP.

Original PHP Implementation

The original PHP code you provided queries the database to retrieve all terms and then performs a Levenshtein distance calculation on each term in PHP. This approach is inefficient as it requires multiple database queries.

$word = strtolower($_GET['term']);

$lev = 0;

$q = mysql_query("SELECT `term` FROM `words`");
while($r = mysql_fetch_assoc($q)) {
    $r['term'] = strtolower($r['term']);

    $lev = levenshtein($word, $r['term']);

    if($lev >= 0 && $lev < 5) {
        $word = $r['term'];
    }
}
登入後複製

Improved MySQL Query

To improve efficiency, you can utilize MySQL's built-in LEVENSHTEIN() function. This function calculates the Levenshtein distance between two strings, eliminating the need for PHP to perform these calculations.

$word = mysql_real_escape_string($word);
$query = "SELECT `term` FROM `words` WHERE LEVENSHTEIN('$word', `term`) BETWEEN 0 AND 4";
登入後複製

This query retrieves all terms whose Levenshtein distance from the given term falls within a specified range (0-4 in this case). By executing this single query, you can obtain the desired results without the overhead of multiple database queries and PHP calculations.

以上是如何在 MySQL 和 PHP 中有效率地計算編輯距離?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板