Search code examples
postgresqlspecial-characters

How to replace multiple special characters in Postgres 9.5


I have a table containing a list of name which might contain special character:

id   name
1    Johän
2    Jürgen
3    Janna
4    Üdyr
...

Is there a function that replaces each character for another specific one? (Not necessarily an unaccented one). Something like this:

SELECT id, function('ä,ü',name,'ae,ue');
Result:

    id   name
    1    Johaen
    2    Juergen
    3    Janna
    4    UEdyr
    ...

Solution

  • No, there are no this function. Probably is not to hard to write optimized C extension what does it. But C language is not necessary always. You can try SQL or PLpgSQL function:

    CREATE OR REPLACE FUNCTION xx(text, text[], text[])
    RETURNS text AS $$
       SELECT string_agg(coalesce($3[array_position($2, c)],c),'')
          FROM regexp_split_to_table($1,'') g(c)
    $$ LANGUAGE sql;
    
    postgres=# select xx('Jürgen', ARRAY['ä','ü'], ARRAY['ae','ue']);
    ┌─────────┐
    │   xx    │
    ╞═════════╡
    │ Juergen │
    └─────────┘
    (1 row)
    

    On my comp it does 6000 transformation under 200ms (but I have developer build of PostgreSQL - it is slower).