Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new line to <p> in php

Tags:

php

nl2br

I currently have a lot of jokes in a database that are formated with nl2br() which produces...

This is just dummy text. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br /><br />
Vestibulum gravida justo in arcu mattis lacinia. Mauris aliquet mi quis diam euismod blandit ultricies ac lacus.
<br /><br />
Aliquam erat volutpat. Donec sed nisi ac velit viverra hendrerit.
<br />
Praesent molestie augue ligula, quis accumsan libero.

I need a php function that rather convert <br /><br /> into a <p></p> and if there is only 1 <br /> then leave it alone. Also trim any whitespace

So the end result would be...

<p>This is just dummy text. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Vestibulum gravida justo in arcu mattis lacinia. Mauris aliquet mi quis diam euismod blandit ultricies ac lacus. </p>
Aliquam erat volutpat. Donec sed nisi ac velit viverra hendrerit.<br />
Praesent molestie augue ligula, quis accumsan libero.

can someone point me in the right direction or give me an simple function that does this? thanks

like image 383
bghouse Avatar asked Feb 15 '13 23:02

bghouse


2 Answers

Use PHP's string replace function to replace all <br /><br /> with </p><p>. http://php.net/manual/en/function.str-replace.php

Sample Code:

$stringWithBRs = nl2br($originalString)
$stringWithPs = str_replace("<br /><br />", "</p>\n<p>", $stringWithBRs);
$stringWithPs = "<p>" . $stringWithPs . "</p>";

Or, you can use the following code without even calling the nl2br() function.

$stringWithPs = str_replace("\n\n", "</p>\n<p>", $originalString);
$stringWithPs = "<p>" . $stringWithPs . "</p>";
like image 128
Tarandeep Gill Avatar answered Nov 01 '22 07:11

Tarandeep Gill


Simply direct convert the original string:

$text=str_replace("<br /><br />", "</p><p>", $original_string);

And in HTML, somewhere like this:

<p>
 <?php echo $text; ?>
</p>
like image 34
ivanaugustobd Avatar answered Nov 01 '22 07:11

ivanaugustobd