preg_replace \\n in string

2019-04-07 00:57发布

问题:

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. :(

回答1:

try this

str_replace("\n", "<br />", $string);


回答2:

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).



回答3:

Have you tried with multiple lines modifier on your RegEx?

preg_replace("/\\n/m", "<br />", $string);