preg_replace() and \n in a string
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).
Try this:
str_replace("\n", "<br />", $string);
Try with the multiple lines modifier on your regular expression:
preg_replace("/\\n/m", "<br />", $string);