Line break with line breaks in HTML paragraphs with PHP

I get text from my MySQL database, which is broken into lines (paragraphs). It is stored in the variable $post_data['content'] . How to print it using line breaks?

The code I use is:

 $post_data['content'] = explode("\n", $post_data['content']); $post = "<p>" . implode("</p><p>", array_values($post_data['content'])) . "</p>"; 

This does not work as much as I want.

If I have such text in the database:

 line 1 paragraph 1, line 2 paragraph 1. line 3 paragraph 2, line 4 paragraph 2, line 5 paragraph 2. 

The code will be displayed as follows (which I am not ):

 <p>line 1 paragraph 1,</p> <p>line 2 paragraph 1.</p> <p>line 3 paragraph 2,</p> <p>line 4 paragraph 2,</p> <p>line 5 paragraph 2.</p> 

I want him to group paragraphs together if there were no spaces between the lines (only one line break). Perhaps something with an array after the explosion?

+6
source share
4 answers

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> 
+15
source

No line explosion.

 $post = "<p>" . nl2br($post_data['content']) . "</p>"; 
0
source

You can try

 $string = 'line 1 paragraph 1, line 2 paragraph 1. line 3 paragraph 2, line 4 paragraph 2, line 5 paragraph 2.'; echo implode("\n",array_map(function ($v) { return sprintf("<p>%s</p>", $v); }, array_filter(explode("\n", $string)))); 
0
source

Another alternative using paragraphs and line breaks:

 $post = ''; $paragraphs = explode("\n\n", $post_data['content']); foreach ($paragraphs as $paragraph) { $post .= '<p>' . nl2br($paragraph) . '</p>'; } 

This should give:

paragraph 1 line 1
paragraph 1 line 2

paragraph 2 line 1

0
source

All Articles