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.
$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;
}
                        Yet another solution:
$string = preg_replace('/\n{2,}/', "</p><p>", trim($string));
$string = preg_replace('/\n/', '<br>',$string);
$string = "<p>{$string}</p>";
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With