Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yilmazerhakan/b947c1471322b4bfc90a to your computer and use it in GitHub Desktop.
Save yilmazerhakan/b947c1471322b4bfc90a to your computer and use it in GitHub Desktop.
MySQL Turkish Slugify
DROP FUNCTION IF EXISTS slugify;
DELIMITER ;;
CREATE DEFINER='root'@'localhost'
FUNCTION slugify (temp_string VARCHAR(200) CHARSET utf8)
RETURNS VARCHAR(200)
DETERMINISTIC
BEGIN
DECLARE x, y , z Int;
DECLARE new_string VARCHAR(200);
DECLARE is_allowed Bool;
DECLARE c, check_char VARCHAR(1);
SET temp_string = LOWER(temp_string);
SET temp_string = REPLACE(temp_string, '&', ' ve ');
# fix Turkish chars
SET temp_string = REPLACE(temp_string, 'ı', 'i');
SET temp_string = REPLACE(temp_string, 'İ', 'i');
SET temp_string = REPLACE(temp_string, 'ç', 'c');
SET temp_string = REPLACE(temp_string, 'Ç', 'c');
SET temp_string = REPLACE(temp_string, 'ğ', 'g');
SET temp_string = REPLACE(temp_string, 'Ğ', 'g');
SET temp_string = REPLACE(temp_string, 'ş', 's');
SET temp_string = REPLACE(temp_string, 'Ş', 's');
SET temp_string = REPLACE(temp_string, 'ö', 'o');
SET temp_string = REPLACE(temp_string, 'Ö', 'o');
SET temp_string = REPLACE(temp_string, 'ü', 'u');
SET temp_string = REPLACE(temp_string, 'Ü', 'u');
SELECT temp_string Regexp('[^a-z0-9-]+') INTO x;
IF x = 1 THEN
SET z = 1;
WHILE z <= CHAR_LENGTH(temp_string) DO
SET c = SUBSTRING(temp_string, z, 1);
SET is_allowed = FALSE;
IF !((ASCII(c) = 45) OR (ASCII(c) >= 48 AND ASCII(c) <= 57) OR (ASCII(c) >= 97 AND ASCII(c) <= 122)) THEN
SET temp_string = REPLACE(temp_string, c, '-');
END IF;
SET z = z + 1;
END WHILE;
END IF;
SELECT temp_string Regexp("^-|-$|'") INTO x;
IF x = 1 THEN
SET temp_string = REPLACE(temp_string, "'", '');
SET z = CHAR_LENGTH(temp_string);
SET y = CHAR_LENGTH(temp_string);
Dash_check: WHILE z > 1 DO
IF STRCMP(SUBSTRING(temp_string, -1, 1), '-') = 0 THEN
SET temp_string = SUBSTRING(temp_string,1, y-1);
SET y = y - 1;
Else
LEAVE Dash_check;
END IF;
SET z = z - 1;
END WHILE;
END IF;
REPEAT
SELECT temp_string Regexp("--") INTO x;
IF x = 1 THEN
SET temp_string = REPLACE(temp_string, "--", "-");
END IF;
UNTIL x <> 1 END REPEAT;
IF LOCATE('-', temp_string) = 1 THEN
SET temp_string = SUBSTRING(temp_string, 2);
END IF;
Return temp_string;
END;;
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment