Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace: converting line breaks into paragraphs

Tags:

regex

php

I want to convert line breaks into paragraphs.

For instance

$string = "1st paragraph

2nd paragraph


3rd paragraph 
";

I want to get,

<p>1st paragraph</p>
<p>2nd paragraph</p>
<p>3rd paragraph</p>

and,

$string = "1st paragraph

2nd paragraph
a line break

3rd paragraph 
";

into,

<p>1st paragraph</p>
<p>2nd paragraph<br/>a line break</p>
<p>3rd paragraph</p>

Is it possible with regex and reg_replace? or something else better - xpath?

I have tried this, but no result yet,

echo preg_replace("'/^(.*?)(<br\s*\/?>\s*)+/'", "<p>$1</p>", nl2br($string));
like image 990
Run Avatar asked Feb 07 '13 22:02

Run


2 Answers

You can do it the other way round: First replace multiple linebreaks by paragraphs, then replace the single linebreaks by <br> elements.

$str = preg_replace('/\n(\s*\n)+/', '</p><p>', $str);
$str = preg_replace('/\n/', '<br>', $str);
$str = '<p>'.$str.'</p>';

You also should normalize the line endings first (windows style to unix style):

function normalize($str) {
    // Normalize line endings
    // Convert all line-endings to UNIX format
    $s = str_replace("\r\n", "\n", $str);
    $s = str_replace("\r", "\n", $s);
    // Don't allow out-of-control blank lines
    $s = preg_replace("/\n{2,}/", "\n\n", $s);
    return $s;
}
like image 193
Yogu Avatar answered Oct 24 '22 00:10

Yogu


Yet another solution:

$string = preg_replace('/\n{2,}/', "</p><p>", trim($string));
$string = preg_replace('/\n/', '<br>',$string);
$string = "<p>{$string}</p>";
like image 4
DiverseAndRemote.com Avatar answered Oct 23 '22 22:10

DiverseAndRemote.com