Is there a mysql stored function out there to create a slug from a url (or any value really).
So my query can be:
SELECT *, SLUG(url) FROM clients
My two cents:
CREATE FUNCTION slugify(str VARCHAR(255))
RETURNS VARCHAR(255)
LANGUAGE SQL
DETERMINISTIC
NO SQL
SQL SECURITY INVOKER
BEGIN
DECLARE slug, allowed_chars VARCHAR(255);
DECLARE current_char VARCHAR(1);
DECLARE pos, len INT;
-- Add here custom replaces
SET slug = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(TRIM(str)), 'ú', 'u'), 'ç', 'c'), 'ğ', 'g'), ' ', '-'), 'é', 'e'), 'è', 'e'), 'ë', 'e'), 'í', 'i'), 'î', 'i'), 'ò', 'o'), 'õ', 'o'), 'ù', 'u'), 'â', 'a'), 'ã', 'a'), 'ö', 'o'), 'ş', 's'), 'ì', 'i'), 'æ', 'ae'), 'à', 'a'), 'ê', 'e'), 'ñ', 'n'), 'ý', 'y'), 'ô', 'o'), 'û', 'u'), 'ï', 'i'), 'ó', 'o'), 'ü', 'u'), 'á', 'a'), 'å', 'a'), 'ä', 'a'), '_', '-');
SET pos = 1;
SET len = CHAR_LENGTH(slug);
SET allowed_chars = 'abcdefghijklmnopqrstuvwxyz0123456789-';
-- Remove not allowed characters
WHILE pos <= len DO
SET current_char = SUBSTRING(slug, pos, 1);
IF LOCATE(current_char, allowed_chars) = 0 THEN
SET slug = REPLACE(slug, current_char, '');
END IF;
SET pos = pos + 1;
END WHILE;
-- Squish dashes
WHILE LOCATE('--', slug) > 0 DO
SET slug = REPLACE(slug, '--', '-');
END WHILE;
RETURN slug;
END;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With