3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = <<<EOT <body> <div class="page-content"> First text <p>Second text</p> <div>Third text</div> <p>More text</p> <h4>Subtitle 1</h4> <p>bla bla</p> <p>bla bla</p> <h4>Subtitle 2</h4> <p>bla bla</p> <p>bla bla</p> </div> </body> EOT; $doc = new DOMDocument(); $doc->loadHTML($html); // Get our node by class name // See https://stackoverflow.com/a/6366390/231316 $finder = new DomXPath($doc); $classname = "page-content"; $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]"); $buf = ''; foreach ($nodes as $node) { foreach ($node->childNodes as $child) { if ($child->nodeName === 'h4') { break; } $buf .= $doc->saveHTML($child); } } echo $buf;
Output for 5.6.40, 7.4.19, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
First text <p>Second text</p> <div>Third text</div> <p>More text</p>

preferences:
84.25 ms | 407 KiB | 5 Q