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>'
);
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>
)
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With