Jacob Brunson
Jacob Brunson

Reputation: 1482

PHP replace double line breaks with <br>

I have a textarea field where I allow users to type in plain text or HTML.

I clean the HTML using HTMLPurify, but I want to add a feature to help users who don't know HTML (and thus use plain-text): convert double line breaks (\n\n, \r\r, \n\r, \r\n) into a <br>. If there are 2 pairs of double line breaks, turn it into 2 <br>s, etc.

Basically:

Hi, this is some text with a SINGLE linebreak after it.
Here's some more text.

This is some text following a double line break.

Will turn into this:

Hi, this is some text with a SINGLE linebreak after it.Here's some more text.
This is some text following a double line break.

Using nl2br() caused problems in that it made using HTML difficult, for example..

<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>

Was turned into

<ul>

<li>List item</li>

<li>List item</li>

<li>List item</li>

</ul>

which caused there to be extra bullet points when there shouldn't be.

Upvotes: 1

Views: 2799

Answers (4)

iambriansreed
iambriansreed

Reputation: 22241

Try nl2br().

nl2br — Inserts HTML line breaks before all newlines in a string

Returns string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r).

Upvotes: 0

Jacob Brunson
Jacob Brunson

Reputation: 1482

I found a solution a while ago, and now I am answering my one question. HTMLPurify has an option for 'auto paragraphing'

AutoFormat.AutoParagraph

Upvotes: 0

Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

It might be HTMLPurify, instead try strip_tags() and use nl2br(), if this works then it is deffinitely HTMLPurify that is causing the problem.

You can also try nl2br() before using HTMLPurify, in that way you would have converted all the \n\r into <br /> before the HTMLPurify and respect the <br /> added.

Upvotes: 1

Levi Hackwith
Levi Hackwith

Reputation: 9332

Does nl2br work for you? http://php.net/manual/en/function.nl2br.php

Upvotes: 1

Related Questions