Sunday, 15 March 2015

php - preg_replace: converting line breaks into paragraphs -



php - preg_replace: converting line breaks into paragraphs -

i want convert line breaks paragraphs.

for instance

$string = "1st paragraph 2nd paragraph 3rd paragraph ";

i want get,

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

and,

$string = "1st paragraph 2nd paragraph line break 3rd paragraph ";

into,

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

is possible regex , reg_replace? or else improve - xpath?

i have tried this, no result yet,

echo preg_replace("'/^(.*?)(<br\s*\/?>\s*)+/'", "<p>$1</p>", nl2br($string));

do other way round: first replace multiple linebreaks paragraphs, replace single linebreaks <br> elements.

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

you should normalize line endings first (windows style unix style):

function normalize($str) { // normalize line endings // convert line-endings unix format $s = str_replace("\r\n", "\n", $s); $s = str_replace("\r", "\n", $s); // don't allow out-of-control blank lines $s = preg_replace("/\n{2,}/", "\n\n", $s); homecoming $s; }

php regex

No comments:

Post a Comment