Skip to content

Instantly share code, notes, and snippets.

@sfaut
Last active April 2, 2023 14:17
Show Gist options
  • Save sfaut/fbf21267ee224f72bf738f61fcb3cdca to your computer and use it in GitHub Desktop.
Save sfaut/fbf21267ee224f72bf738f61fcb3cdca to your computer and use it in GitHub Desktop.
Removes diacritics from input string
-- Removes diacritics from input string
-- Author : sfaut <https://github.com/sfaut>
-- Publication date : 2023-01-07
-- Tested with MySQL 8.0.31 (@@sql_mode='ANSI,TRADITIONAL')
DELIMITER ;;
CREATE FUNCTION REMOVE_DIACRITICS(input TEXT) RETURNS TEXT CHARSET utf8mb4
DETERMINISTIC
COMMENT 'Removes diacritics from input string'
BEGIN
DECLARE length INTEGER UNSIGNED DEFAULT CHAR_LENGTH(input);
DECLARE i INTEGER UNSIGNED DEFAULT 0;
DECLARE c VARCHAR(1); -- Pas de CHAR(1) car perte espace
DECLARE p INT UNSIGNED;
DECLARE buffer TEXT DEFAULT '';
DECLARE with_diacritics TINYTEXT DEFAULT 'àáâãäåæçèéêëìíîïñòóôõöøšùúûüýÿžÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØŠÙÚÛÜÝŸŽ';
DECLARE without_diacritics TINYTEXT DEFAULT 'aaaaaaaceeeeiiiinoooooosuuuuyyzAAAAAAACEEEEIIIINOOOOOOSUUUUYYZ';
WHILE i < length DO
SET i = i + 1;
SET c = SUBSTRING(input FROM i FOR 1);
SET p = POSITION(c IN with_diacritics COLLATE utf8mb4_0900_as_cs);
IF p > 0 THEN
SET c = SUBSTRING(without_diacritics FROM p FOR 1);
END IF;
SET buffer = CONCAT(buffer, c);
END WHILE;
RETURN buffer;
END;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment