Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace() and \n in a string

For some reason, 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.

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

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

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

like image 702
Thomas Clayson Avatar asked Jul 05 '11 08:07

Thomas Clayson


2 Answers

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, the preg engine will interpret '/\n/' as a newline character (I am not exactly sure which one/s).

like image 193
Salman A Avatar answered Nov 09 '22 21:11

Salman A


Try this:

str_replace("\n", "<br />", $string);
like image 36
rackemup420 Avatar answered Nov 09 '22 23:11

rackemup420