Jamie Hunt
Jamie Hunt

Reputation: 33

preg_replace and linebreaks

I have a big area of text that I wish to convert to valid HTML. This includes adding a paragraph tag to each new paragraph, how can I do this with PHP? For example adding line breaks like this:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

goes to

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>

Can this be achived with preg_replace??

Thanks

Upvotes: 1

Views: 978

Answers (4)

undone
undone

Reputation: 7888

$result = "<p>" . str_replace("\r\n","</p><p>",$text) . "</p>";

(demo)

Upvotes: 1

Daniel
Daniel

Reputation: 1151

This way you don't have to worry about the different types of vertical line breaks (\n or \r or \f or a combination):

$output = '<p>' . preg_replace('/\v+/', '</p><p>', $input) . '</p>';

You might also find this site helpful for testing: http://www.gummydev.com/regex/

Upvotes: 0

ioseb
ioseb

Reputation: 16951

I think this is what you want:

  function nl2p($input) {
    return preg_replace('~^\s*(.*?)\s*$~sm', '<p>$1</p>', $input);
  }

Upvotes: 2

sascha
sascha

Reputation: 4690

Maybe this helps http://php.net/manual/de/function.nl2br.php#78883

<?php
function nls2p($str)
 {
   return str_replace('<p></p>', '', '<p>' 
         . preg_replace('#([\r\n]\s*?[\r\n]){2,}#', '</p>$0<p>', $str) 
         . '</p>');
 }
?>

Upvotes: 0

Related Questions