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));
You can do it the other way round: First replace multiple linebreaks by paragraphs, then replace the single linebreaks by
<br>elements.You also should normalize the line endings first (windows style to unix style):