How can I replace newline or \r\n with <br/>?
There is already the nl2br()
function that inserts <br>
tags before new line characters:
Example (codepad):
<?php// Won't work$desc = 'Line one\nline two';// Should work$desc2 = "Line one\nline two";echo nl2br($desc);echo '<br/>';echo nl2br($desc2);?>
But if it is still not working make sure the text $desciption
is double-quoted.
That's because single quotes do not 'expand' escape sequences such as \n
comparing to double quoted strings. Quote from PHP documentation:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Try using this:
$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);
You may have real characters "\" in the string (the single quote strings, as said @Robik).
If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:
str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description);