Skip to content

Instantly share code, notes, and snippets.

@ano
Created April 8, 2023 07:30
Show Gist options
  • Save ano/e244ff13292481bcf40ea24719375620 to your computer and use it in GitHub Desktop.
Save ano/e244ff13292481bcf40ea24719375620 to your computer and use it in GitHub Desktop.
A MySQL user defined function called slugify() that takes in a string like “John’s a great guy” and convert it to “johns-a-great-guy”
DELIMITER //
CREATE FUNCTION slugify(input_text VARCHAR(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
DECLARE output_text VARCHAR(255);
SET output_text = LOWER(input_text);
SET output_text = REPLACE(output_text," ","-");
SET output_text = REPLACE(output_text,"'","");
SET output_text = REPLACE(output_text,"’","");
SET output_text = REPLACE(output_text,"’","");
SET output_text = REPLACE(output_text,"’","");
SET output_text = REPLACE(output_text,"’","");
SET output_text = REPLACE(output_text,"’","");
SET output_text = REPLACE(output_text,"‘","");
SET output_text = REPLACE(output_text,"(","");
SET output_text = REPLACE(output_text,")","");
SET output_text = REPLACE(output_text,"[","");
SET output_text = REPLACE(output_text,"]","");
SET output_text = REPLACE(output_text,"{","");
SET output_text = REPLACE(output_text,"}","");
SET output_text = REPLACE(output_text,"<","");
SET output_text = REPLACE(output_text,">","");
SET output_text = REPLACE(output_text,"&","");
SET output_text = REPLACE(output_text,"\"","");
SET output_text = REPLACE(output_text,"’","");
RETURN output_text;
END //
DELIMITER ;
To use this function, you can execute the following command:
SELECT slugify("John's a great guy");
This will output: johns-a-great-guy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment