preg_replace \n in string

2019-04-07 01:25发布

for some reason this: preg_replace("/\\n/", "<br />", $string); isn't working.

The string outputs in this format: blah blah blah\nblah blah blah even after the preg replace.

All I want to do is change if for a <br />.

nl2br() doesn't work either, but as its just text I wasn't sure if it should.

Thanks

** Update **

the preg_replace works on a word in the string. :(

3条回答
等我变得足够好
2楼-- · 2019-04-07 01:28

try this

str_replace("\n", "<br />", $string);
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-07 01:42

If you want to replace the literal \n and not the actual new line, Try:

<?php
echo preg_replace("/\\\\n/", "<br />", 'Hello\nWorld');

Notice the number of backslashes. The double-quote enclosed string /\\\\n/ is interpreted by the PHP engine as /\\n/. This string when passed on to the preg engine is interpreted as the literal \n.

Note that both PHP will interpret "\n" as the ASCII character 0x0A. Likewise, preg engine will interpret '/\n/' as a newline character (not exactly sure which one/s).

查看更多
爷的心禁止访问
4楼-- · 2019-04-07 01:51

Have you tried with multiple lines modifier on your RegEx?

preg_replace("/\\n/m", "<br />", $string);
查看更多
登录 后发表回答