PHP breaks each paragraph into an array

I want to break each paragraph into an array.

My current approach does not work:

$paragraphs = preg_split( '|</p>|', $text, PREG_SPLIT_OFFSET_CAPTURE ); 

How can I get from this:

 $text = <<<TEXT <p>Hello!</p> <p style="border: 1px solid black;">How are you,<br /> today?</p> TEXT; 

to that

 $paragraphs = array( '<p>Hello!</p>', '<p style="border: 1px solid black;">How are you,<br /> today?</p>' ); 
+7
html split php regex
source share
4 answers

You can use DOMDocument () for this, as shown below.

  <?php $text = <<<TEXT <p>Hello!</p> <p style="border: 1px solid black;">How are you,<br /> today?</p> TEXT; $dom = new DOMDocument(); $paragraphs = array(); $dom->loadHTML($text); foreach($dom->getElementsByTagName('p') as $node) { $paragraphs[] = $dom->saveHTML($node); } print_r($paragraphs); ?> 

Exit

 Array ( [0] => <p>Hello!</p> [1] => <p style="border: 1px solid black;">How are you,<br> today?</p> ) 
+8
source share

You have forgotten the limit attribute, and the flag is PREG_SPLIT_DELIM_CAPTURE

 $text = <<<TEXT <p>Hello!</p> <p style="border: 1px solid black;">How are you,<br /> today?</p> TEXT; $paragraphs = preg_split( '|(?<=</p>)\s+(?=<p)|', $text, -1, PREG_SPLIT_DELIM_CAPTURE); // here __^^ print_r($paragraphs); 

Output:

 Array ( [0] => <p>Hello!</p> [1] => <p style="border: 1px solid black;">How are you,<br /> today?</p> ) 
+2
source share

There may be many. You also follow the instructions below.

 $array = explode("</p>", $text); 

This will break your text every time </p> in an array line. Then apply the following loop to add </p>

 foreach($array as $row) { $paragraphs[] = $row."</p>"; } 

print_r ($ paragraphs);

+2
source share

If you are sure that each closing tag will be exact

you can use explode:
  $paragraphs = explode('</p>', $text); 

Otherwise, if there might be some space, you need to use a regular expression:

  $paragraphs = preg_split('/<\/\s*p\s*>/', $text); 
0
source share

All Articles