3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = <<<HTML <h2>My title 1</h2> <h3>Sub-heading</h3> <p>...<span><a href='#'>...</a></span></p> <div>...</div> <h2>My title 2</h2> <p>No sub-heading here :O</p> <h3>But here</h3> <p>No link</p> <h2>And so on...</h2> <p>...</p> <div><h2>This is nested</h2></div> HTML; $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXpath($doc); $domNodeList = $xpath->query('/html/body/h2'); $sets = array(); foreach($domNodeList as $element) { // Save the h2 $set = array($element); // Loop the siblings unit the next h2 while ($element = $element->nextSibling) { if ($element->nodeName === "h2") { break; } // if Node is a DOMElement if ($element->nodeType === 1) { $set[] = $element; } } $sets[] = $set; } var_dump($sets);

preferences:
57.04 ms | 402 KiB | 5 Q