Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AnatoliyViktorovich's avatar

How to turn "\n" into "<br>" ?

I bet there is some built in function but can't find anything about it. I copy text from a page, I insert it into a textarea field of my form and save to db, but when I show it on a page it's unformatted. PLease help.

0 likes
6 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To turn "\n" into "", you can use the PHP function nl2br(). This function replaces all occurrences of newlines (\n) with HTML line breaks (). Here's an example:

$text = "This is a\nmultiline\ntext.";
$formattedText = nl2br($text);
echo $formattedText;

This will output:

This is a<br>
multiline<br>
text.

So in your case, you can use nl2br() to format the text before displaying it on the page. Here's an example:

// Get the text from the database
$text = $row['text'];

// Format the text with nl2br
$formattedText = nl2br($text);

// Display the formatted text
echo $formattedText;

This will replace all newlines in the text with HTML line breaks, so it will be displayed with proper formatting on the page.

1 like
AnatoliyViktorovich's avatar

it looks like it doesn't work in blade template. {{ nl2br($post->body) }} displays as word<br />word<br />word

click's avatar

@AnatoliyViktorovich I don't know what your function _() does (translate is with double underscores __()). But please don't do this as this might open up your system to XSS attacks.

You should first escape all of the content with e(), after that turn all new lines into <br /> with nl2br() like this:

{!! nl2br(e($post->body)) !!}

This way all funky possibly dangerous tags, css, and javascript is escaped.

1 like

Please or to participate in this conversation.