Q:

Converting new lines to 

I wanted to figure out a good way to replace new line characters to br's, the only way I could make it work is with "3x-replace" solution, which works (and I guess it put into function is not that verbose), but I was wondering if there is more elegant solution.
Thanks for any feedback. 
--
-- Works, but seems a little heavy with 3 nested replace commands
--
CREATE OR REPLACE FUNCTION test_nl2br(text_in text) RETURNS text AS
$$
    SELECT replace(
        replace( 
            replace(text_in, E'\r\n', '<br />'), E'\n', '<br />'
        ), E'\r', '<br />'
    );
$$
LANGUAGE SQL;

--
-- Test with a few values
--
WITH example_set AS (
    SELECT * FROM (
        VALUES
            (E'a\nb'),
            (E'a\r\nb'),
            (E'a\rb'),
            (E'a\nb\rc\r\nd')
        ) AS x (test)
)
SELECT test_nl2br(test::text) AS result FROM example_set;

A:

you can use regexp_replace function 
CREATE OR REPLACE FUNCTION test_nl2br(text_in text)
RETURNS text AS $$                 
   SELECT regexp_replace($1, E'\r\n|\n|\r', '<br />', 'g');
$$ LANGUAGE SQL;

