First replace the line breaks with <br /> :
$post = nl2br($post_data['content']);
Then replace double <br /> with the tag to close and open the paragraph (the original line break is supported by nl2br , so I use a regular expression that matches all line break styles):
$post = '<p>' . preg_replace('#(<br />[\r\n]+){2}#', '</p><p>', $post) . '</p>';
Note that this is XHTML syntax, if you want to have HTML, change the code as follows:
$post = nl2br($post_data['content'], false); $post = '<p>' . preg_replace('#(<br>[\r\n]+){2}#', '</p><p>', $post) . '</p>';
Test:
$post_data['content'] = <<<TXT line 1 paragraph 1, line 2 paragraph 1. line 3 paragraph 2, line 4 paragraph 2, line 5 paragraph 2. TXT; $post = nl2br($post_data['content'], false); $post = '<p>' . preg_replace('#(<br>[\r\n]+){2}#', "</p>\n\n<p>", $post) . '</p>'; echo $post;
Test Output:
<p>line 1 paragraph 1,<br> line 2 paragraph 1.</p> <p>line 3 paragraph 2,<br> line 4 paragraph 2,<br> line 5 paragraph 2.</p>
source share