Newline <p> in php

I currently have a lot of jokes in the database that are generated 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 would rather convert <br /><br />

to <p></p>

, and if there is only 1 <br />

, leave it alone. Also trim any spaces

So the end result will 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 anyone point me in the right direction or give me a simple function that does this? thank

+3


source to share


5 answers


Use PHP's string replace function to replace everything <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>";

      

+3


source


Just converting the original string directly:

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

      



And in HTML, something like this:

<p>
 <?php echo $text; ?>
</p>

      

+3


source


One line:

$sNewString = implode('</p><p>',explode('<br /><br />', nl2br($sOriginalString)))

      

Explanation:

  • Convert line breaks to br.
  • Split the string into an array with these br
  • Glue the array back to the string by inserting P tags between the array elements
+2


source


$new = '';
foreach(explode("\n<br /><br />\n", $text) as $p) // split by double newlines
    $new.= "<p>$p</p>\n"; // and convert each part to a paragraph


// or if you want to keep it in a single line
$new = join(array_map(function($p){return "<p>$p</p>\n";}, explode("\n<br /><br />\n", $text)));

      

0


source


Try

$old_string = preg_replace("/[\r\n]/","</p><p>",$old_string);
$new_string = "<p>" . $old_string . "</p>";
echo $new_string;

      

0


source







All Articles