I would like to find an elegant way to emulate the behavior of MySQL\'s subtring_index() function in Postgres.
In MySQL, it\'s as easy as:
mysql>
Here is how I implement (or emulate) MySQL's subtring_index() in PostgreSQL
CREATE OR REPLACE FUNCTION public.substring_index (
str text,
delim text,
count integer = 1,
out substring_index text
)
RETURNS text AS
$body$
BEGIN
IF count > 0 THEN
substring_index = array_to_string((string_to_array(str, delim))[:count], delim);
ELSE
DECLARE
_array TEXT[];
BEGIN
_array = string_to_array(str, delim);
substring_index = array_to_string(_array[array_length(_array, 1) + count + 1:], delim);
END;
END IF;
END;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 5;
and here is the example from mysql's documentation;
postgres=# SELECT substring_index('www.mysql.com', '.', 2);
substring_index
-----------------
www.mysql
(1 row)
postgres=# SELECT substring_index('www.mysql.com', '.', -2);
substring_index
-----------------
mysql.com
(1 row)
Always take the time to skim the manuals.
http://www.postgresql.org/docs/current/static/functions-string.html
If split_part(string text, delimiter text, field int)
doesn't do what you want (and more, if I understand your MySQL function) then you'll need to explain where and why.