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

brentxscholl's avatar

Preserve Line Breaks in Textarea Input

I have a textarea input in my form. Is there a way to preserve the line breaks when saving to the DB? When ever I use line breaks they are replaced with spaces and the text is saved as one paragraph.

example:

If I write this in the textarea:

" Here is a sentence. Here is another. here is one more.

This is a new paragraph. Here is a new sentence. Here is another.

Another new paragraph. And here is a sentence"

I want to save it like this:

" Here is a sentence. Here is another. here is one more.

This is a new paragraph. Here is a new sentence. Here is another.

Another new paragraph. And here is a sentence"

But instead I get this:

" Here is a sentence. Here is another. here is one more. This is a new paragraph. Here is a new sentence. Here is another. Another new paragraph. And here is a sentence"

0 likes
6 replies
bashy's avatar
bashy
Best Answer
Level 65

I'm sure it should format it but it depends how you're displaying it. Did you use an editor (or markdown) to format the text or is it just from a plain textarea input with nothing special on it?

Are you doing anything to the data when it saves? For me it goes in as is and I can escape any unwanted html tags or elements and it's fine.

nl2br($content) can change \r\n to < br >

5 likes
brentxscholl's avatar

@bashy Nothing special with textarea or when I'm saving it to the DB

nl2br($content) did the trick. Thanks a lot!!

alexmansour's avatar

@bashy nl2br($content) it's working well with saving multi-line text but when I leave blank line in the middle of the paragraph nothing got saved to the db.

For example:

Laravel

PHP Whatever

Note the second line is blank

Any suggestions ?

bashy's avatar

@alexmansour Empty line breaks? It's always worked for me but I use Markdown/BBCode nowadays so this is sorted in the parser.

alexmansour's avatar

@bashy thanks for your reply.

Yes empty lines, there is a case where we need to have empty lines for example when you write a letter or email message.

So we still need to use nl2br($content) when we use markdown/bbcode ?

bashy's avatar

BBCode and Markdown should use < p > tags for paragraphs anyway.

1 like

Please or to participate in this conversation.