Maison >base de données >tutoriel mysql >Comment intégrer la fonction Levenshtein dans MySQL pour les applications de recherche PHP ?

Comment intégrer la fonction Levenshtein dans MySQL pour les applications de recherche PHP ?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-12-07 18:16:12521parcourir

How to Integrate the Levenshtein Function into MySQL for PHP Search Applications?

Installation de la fonction Levenshtein dans MySQL

Problème :

Comment la fonction de distance Levenshtein peut-elle être incorporé à MySQL pour être utilisé dans la recherche basée sur PHP applications ?

Solution :

Ajout de la fonction Levenshtein

Pour ajouter la fonction Levenshtein à MySQL, suivez ces étapes en utilisant MySQL Workbench :

  1. Connectez-vous à votre MySQL serveur.
  2. Exécutez l'instruction suivante :
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 <p><strong>Exemple d'utilisation</strong></p><p>Une fois la fonction Levenshtein ajoutée, vous pouvez l'utiliser en PHP comme suit :</p><pre class="brush:php;toolbar:false">$query = "SELECT levenshtein('abcde', 'abced')";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row['levenshtein(abcde, abced)']; // Output: 2

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn