3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = '<div id="top"><h3><span class="header" id="first_set">My Heading</span></h3> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <h3><span class="header" id="second_set">My Second Heading</span></h3> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <h3><span class="header" id="third_set">My Third Heading</span></h3> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> </div>'; $doc = new DOMDocument(); $doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $div = $doc->createElement('div'); $node = $doc->getElementById('top'); $xpath = new DOMXPath($doc); $headers = 0; foreach ($xpath->query('./*', $node) as $child) { switch ($child->nodeName) { case 'h3': $headers++; if ($headers == 2) { $node->replaceChild($div, $child); $div->appendChild($child); } else if ($headers == 3) { break 2; } break; case 'ul': if ($headers == 2) $div->appendChild($child); break; default: // if a non-ul element after the 2nd header, exit the loop if ($headers == 2) break 2; break; } } echo $doc->saveHTML();
Output for 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.4 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.4.16, 8.5.0 - 8.5.1
<div id="top"><h3><span class="header" id="first_set">My Heading</span></h3> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <div><h3><span class="header" id="second_set">My Second Heading</span></h3><ul><li>Text Text Text</li></ul><ul><li>Text Text Text</li></ul><ul><li>Text Text Text</li></ul></div> <h3><span class="header" id="third_set">My Third Heading</span></h3> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> <ul><li>Text Text Text</li></ul> </div>
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
203.24 ms | 408 KiB | 5 Q