gpt4 book ai didi

postgresql - 将新行转换为

转载 作者:行者123 更新时间:2023-11-29 14:19:29 25 4
gpt4 key购买 nike

我想找出一种将新行字符替换为 br 的好方法,唯一能让它工作的方法是使用“3x-replace”解决方案,该解决方案有效(而且我猜它投入功能并不那么冗长), 但我想知道是否有更优雅的解决方案。

感谢任何反馈。

--
-- 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;

最佳答案

你可以使用regexp_replace函数

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;

关于postgresql - 将新行转换为 <br/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34649619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com