Forum Moderators: coopster

Message Too Old, No Replies

line breaks to paragraphs

         

formasfunction

1:16 am on Oct 26, 2007 (gmt 0)

10+ Year Member



I found this function in the comments of nl2br at php.net:

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

echo nl2br(nls2p("Paragraph1\n\nParagraph2\n line1\n line2\n"));
?>

I'm using it on a textarea and for some reason I'm getting both the <p> tags and ALL of the <br> tags so instead of \n\n turning into a paragraph it's turning into a paragraph with two breaks. Is the nls2p function not killing off the \n's that it's supposed to be replacing? I'm open to using another function in place of this, this just seemed to be the easiest I'd found.

Receptional Andy

8:10 pm on Oct 28, 2007 (gmt 0)



It may be overkill for what you want, but wordpress includes a function to do just what you want (wpautop). You can view the function in the wordpress formatting source code [trac.wordpress.org].