Installing the Levenshtein Function in MySQL
Problem:
How can the Levenshtein distance function be incorporated into MySQL for use in PHP-based search applications?
Solution:
Adding the Levenshtein Function
To add the Levenshtein function to MySQL, follow these steps using MySQL Workbench:
CREATE FUNCTION levenshtein(s1 VARCHAR(255), s2 VARCHAR(255)) RETURNS INT BEGIN DECLARE len1 INT; DECLARE len2 INT; DECLARE i INT; DECLARE j INT; DECLARE c INT; DECLARE cost INT; DECLARE d INT; DECLARE tmp INT; SET len1 = LENGTH(s1); SET len2 = LENGTH(s2); DECLARE matrix[len1 + 1][len2 + 1] INT; FOR i = 0 TO len1 DO SET matrix[i][0] = i; END FOR; FOR j = 0 TO len2 DO SET matrix[0][j] = j; END FOR; FOR i = 1 TO len1 DO FOR j = 1 TO len2 DO IF s1[i] = s2[j] THEN SET cost = 0; ELSE SET cost = 1; END IF; SET d = matrix[i - 1][j] + 1; SET c = matrix[i][j - 1] + 1; SET tmp = matrix[i - 1][j - 1] + cost; IF d < c THEN IF d < tmp THEN SET matrix[i][j] = d; ELSE SET matrix[i][j] = tmp; END IF; ELSE IF c < tmp THEN SET matrix[i][j] = c; ELSE SET matrix[i][j] = tmp; END IF; END IF; END FOR; END FOR; RETURN matrix[len1][len2]; END
Example Usage
Once the Levenshtein function is added, you can use it in PHP as follows:
$query = "SELECT levenshtein('abcde', 'abced')"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); echo $row['levenshtein(abcde, abced)']; // Output: 2
The above is the detailed content of How to Integrate the Levenshtein Function into MySQL for PHP Search Applications?. For more information, please follow other related articles on the PHP Chinese website!