在MySQL中安装Levenshtein函数
问题:
Levenshtein距离函数如何合并到 MySQL 中以用于基于 PHP 的搜索
解决方案:
添加 Levenshtein 函数
要将 Levenshtein 函数添加到 MySQL,请按照以下步骤使用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
使用示例
添加Levenshtein函数后就可以使用了在 PHP 中如下:
$query = "SELECT levenshtein('abcde', 'abced')"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); echo $row['levenshtein(abcde, abced)']; // Output: 2
以上是如何将 Levenshtein 函数集成到 MySQL 中以用于 PHP 搜索应用程序?的详细内容。更多信息请关注PHP中文网其他相关文章!