Thomas McCabe Thomas McCabe - 1 year ago 117
PHP Question

How to replace \r & \n with <br/>?

Trying to simply replace some new lines. Have tried 3 different ways and I get no 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?

Answer Source

There is already nl2br() function that replaces inserts <br> tags before new line characters:

Example (codepad):

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download