92

I am trying to simply replace some new lines and have tried three different ways, but I don't get any change:

$description = preg_replace('/\r?\n|\r/', '<br/>', $description);
$description = str_replace(array("\r\n", "\r", "\n"), "<br/>", $description);
$description = nl2br($description);

These should all work, but I still get the newlines. They are double: "\r\r". That shouldn't make any of these fail, right?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
theflowersoftime
  • 2,546
  • 3
  • 24
  • 32

10 Answers10

148

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robik
  • 6,047
  • 4
  • 31
  • 41
  • 1
    Look closer, he the OP specifically shows that they attempted to use `nl2br` and that it didn't work. – Tim Bielawa May 10 '11 at 06:38
  • Just tried to run nl2br on a string with double carriage returns, and it worked fine. – Decko May 10 '11 at 06:41
  • 1
    Look at my edit @ThomasMcCabe. I've added some (maybe) useful info. – Robik May 10 '11 at 06:42
  • 32
    Please note that `nl2br` does **NOT REPLACE** but instead **INSERTS** before newlines, which LEAVES the nl characters and ADDS br before them. – Brock Hensley May 02 '13 at 14:30
  • but if we have a file with line breaks and we want to read it by a php script and interpret those break lines , how to do it ? – user3911183 May 22 '15 at 10:31
70

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
afarazit
  • 4,907
  • 2
  • 27
  • 51
  • 15
    a faster alternative could be `$description = str_replace(["\r\n", "\r", "\n"], "
    ", $description)` taken from [this answer](http://stackoverflow.com/a/20717751/2431281)
    – Keale Jul 29 '15 at 09:33
  • 10
    (One could also use just [`/\R/` for all CR/LF](https://nikic.github.io/2011/12/10/PCRE-and-newlines.html) linebreak combinations.) – mario Aug 13 '15 at 19:28
19

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);
regilero
  • 29,806
  • 6
  • 60
  • 99
10

Try this:

echo str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $description);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • 8
    Read about PHP [strings](http://php.net/manual/en/language.types.string.php). [`'\r\n'`](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single) is not the same as [`"\r\n"`](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double). – axiac Feb 22 '18 at 10:05
  • Thanks @axiac, I dont have time to test, But you mean It should be something like `"\r\n"` right ? – l2aelba Feb 22 '18 at 12:49
  • This code-only answer is misleading to naive researchers. – mickmackusa Oct 19 '22 at 07:55
6

nl2br() worked for me, but I needed to wrap the variable with double quotes:

This works:

$description = nl2br("$description");

This doesn't work:

$description = nl2br($description);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
infografnet
  • 3,749
  • 1
  • 35
  • 35
6

nl2br() as you have it should work fine:

$description = nl2br($description);

It's more likely that the unclosed ' on the first line of your example code is causing your issue. Remove the ' after $description...

...$description');
sakatc
  • 309
  • 1
  • 2
  • 9
3

This will work for sure:

str_replace("\\r", "<br />", $description); 
str_replace("\\n", "<br />", $description); 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Radeck
  • 31
  • 1
  • Absolutely incorrect suggestion. "foo\\r\\nbar" will become "foobar" instead of "foo
    bar". Prior to replace html renders "foo bar".
    – Artemix Sep 14 '12 at 13:55
  • Meh. Works for some specific cases where the input is of a known format. –  May 06 '13 at 14:48
2
$description = nl2br(stripcslashes($description));
softcod.com
  • 554
  • 5
  • 8
  • 1
    The explanation is missing from this answer. – mickmackusa Mar 26 '20 at 03:11
  • The answer from @softcod.com allows to replace the string from a query, for example:
    `$description = nl2br(stripcslashes($row["description"]));`
    [stripcslashes](https://www.php.net/manual/en/function.stripcslashes.php) returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.
    – luguen Jan 07 '23 at 17:14
1

I think str_replace(array("\\r\\n", "\\r", "\\n"), " ", $string); will work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThunderStorm
  • 155
  • 1
  • 1
  • 12
-3

If you are using nl2br, all occurrences of \n and \r will be replaced by <br>. But if (I don’t know how it is) you still get new lines you can use

str_replace("\r","",$description);
str_replace("\n","",$description);

to replace unnecessary new lines by an empty string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131