Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP split each paragraph into array

I want to split each paragraph into an array.

My current approach doesn't 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 this

$paragraphs = array(
     '<p>Hello!</p>',
     '<p style="border: 1px solid black;">How are you,<br /> today?</p>'
);
like image 249
pbaldauf Avatar asked Apr 30 '15 11:04

pbaldauf


2 Answers

You can use DOMDocument() for this like as follows

 <?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);
?>

Output

Array
(
  [0] => <p>Hello!</p>
  [1] => <p style="border: 1px solid black;">How are you,<br> today?</p>
)
like image 100
Shijin TR Avatar answered Oct 24 '22 14:10

Shijin TR


You've forgotten the attribut limit 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>
)
like image 35
Toto Avatar answered Oct 24 '22 12:10

Toto