Skip to content
Advertisement

Replace a whole div code (with divs inside) with different code using php

I am getting a code of a page using ob_buffer and i try to replace all divs inside the page that contain the class locked-content.

While it’s easy with jquery the problem is that with php is a bit harder. Let say for example i have this html code

<div class='class'> cool content </div>

<div class='class more-class life-is-hard locked-content'>

    <div class='cool-div'></div>
    <div class='anoter-cool-div'></div>

    some more code here

</div>

<div class='class'> cool content </div>

Now it seems like a complex task, I think i need to detect somehow how many divs are open after the div with the class ‘locked-content’ and then count how many closed div there are and when the wanted div was closed and then replace the code with new code while looping the code in case the div exists more than once.

Anyone has an idea on how to do something like this? Thanks

Advertisement

Answer

You can do it via DOMXPath:

$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);
$node = $xpath->query('//div[contains(@class, "locked-content")]');

foreach ($nodes as $node) {
    foreach ($node->childNodes as &$cNode) {
        if ($cNode instanceOf DOMElement && $cNode->tagName === 'div') {
            $cNode->replaceWith(/* Whatever */);
        }
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement