PostgreSQL provides a built-in function for character wise string replacement:
select translate('abcdefghijkl', 'ace', '123');
translate
--------------
1b2d3fghijkl
pgstrtranslate extends it with multi-character replacement. It takes 4 arguments and returning a text.
CREATE OR REPLACE FUNCTION public.pgstrtranslate(
fullsearch boolean,
t text,
search text[],
replacement text[])
RETURNS text AS
'$libdir/pgstrtranslate', 'pgstrtranslate'
LANGUAGE c IMMUTABLE STRICT;
select pgstrtranslate(false, --non-fullsearch
'abcdefghijkl', --original string
array['ab', 'efg', '2cd']::text[], --array of searchs
array['012', '3', '78']::text[]); --array of replacement
translate
--------------
012cd3hijkl
'abcdefghijkl' -> '012cd3hijkl'
Note that '2cd' does not match original string.
select pgstrtranslate(true, --fullsearch
'abcdefghijkl', --original string
array['ab', 'efg', '2cd']::text[], --array of searchs
array['012', '3', '78']::text[]); --array of replacement
translate
--------------
01783hijkl
Replace 'ab' with '012': 'abcdefghijkl' -> '012cdefghijkl'
Replace 'efg' with '3': '012cdefghijkl' -> '012cd3hijkl'
Replace '2cd' with '78': '012cd3hijkl' -> '01783hijkl'
- Clone or download source code from https://github.com/AbdulYadi/pgstrtranslate.git. Extract it.
- If necessary, modify PG_CONFIG path according to your specific PostgreSQL installation location.
- Build as usual:
$ make
$ make install
- On successful compilation, install this extension in PostgreSQL environment
$ create extension pgstrtranslate;