Skip to content

Instantly share code, notes, and snippets.

@kmatt
Forked from abn/slugify.postgres.sql
Last active February 1, 2023 12:51
Show Gist options
  • Save kmatt/26447f55a3a099e604cf192ae2b3af4d to your computer and use it in GitHub Desktop.
Save kmatt/26447f55a3a099e604cf192ae2b3af4d to your computer and use it in GitHub Desktop.
A slugify function for postgres
-- original source: https://medium.com/adhawk-engineering/using-postgresql-to-generate-slugs-5ec9dd759e88
-- https://www.postgresql.org/docs/9.6/unaccent.html
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE OR REPLACE FUNCTION public.slugify(v TEXT) RETURNS TEXT
LANGUAGE plpgsql
STRICT IMMUTABLE AS
$function$
BEGIN
-- 1. trim trailing and leading whitespaces from text
-- 2. remove accents (diacritic signs) from a given text
-- 3. lowercase unaccented text
-- 4. replace non-alphanumeric with a hyphen
-- 5. trim leading and trailing hyphens
RETURN trim(BOTH '-' FROM regexp_replace(lower(unaccent(trim(v))), '[^a-z0-9\\-]+', '-', 'gi'));
END;
$function$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment