3v4l.org

run code in 200+ php & hhvm versions
<?php $html = <<<HTML <div class="somethingelse">content</div> <div class="product-fields"> <div class="product-field product-field-type-R"> <span class="product-fields-title-wrapper"><span class="product-fields-title"><strong>Related Products</strong></span> <span title="" class="hasTooltip" data-original-title="&lt;strong&gt;Related Products&lt;/strong&gt;&lt;br /&gt;COM_VIRTUEMART_RELATED_PRODUCTS_TIP"><img alt="Tooltip" src="/j34/media/system/images/tooltip.png"></span></span> <span class="product-field-display"><a target="blank" title="Test Product 1" href="/j34/index.php/shops/c1/t1-detail">Test Product 1</a></span><span class="product-field-desc">Custom prototype for related products</span> </div> <div class="mickmackusa">Not the drone you're looking for</div> <div class="product-field matrix-agent-smith product-field-type-R"> <span>Find them and destroy them</span> </div> </div> <div class="someothercontainer">Text</div> HTML; $getRelatedProduct = "Flashy, shiny, new"; libxml_use_internal_errors(true); $dom = new DOMDocument; $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $element = $dom->createElement('div', $getRelatedProduct); $xpath = new DOMXPath($dom); $nodes = $xpath->query("//div[contains(@class, 'product-fields')]/div[contains(@class, 'product-field') and contains(@class, 'product-field-type-R')]"); for ($i = $nodes->length - 1; $i >= 0; --$i) { // when removing nodes from DOM, work in reverse order for stability $node = $nodes->item($i); if ($i) { //$trailing_whitespace = $node->nextSibling; $node->parentNode->removeChild($node); // remove any qualifying element that IS NOT the first element //$trailing_whitespace->parentNode->removeChild($trailing_whitespace); // optionally remove line returns after removed tags } else { $node->parentNode->replaceChild($element, $node); // replace the first element with the generated element } } echo $dom->saveHTML();
based on iKgiQ
Output for 5.6.38 - 7.2.12
<div class="somethingelse">content<div class="product-fields"> <div>Flashy, shiny, new</div> <div class="mickmackusa">Not the drone you're looking for</div> </div><div class="someothercontainer">Text</div></div>