Skip to content

Instantly share code, notes, and snippets.

@tanerdogan
Created October 15, 2014 09:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tanerdogan/748877e68b897be04fe7 to your computer and use it in GitHub Desktop.
Save tanerdogan/748877e68b897be04fe7 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 ;
@ebsaral
Copy link

ebsaral commented Jan 10, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment