0

Let's say I have a string like this

    <div class="grandpa">
        <div class="pa">
            <p> Some lorem ipsum...</p>
            <div class="we_dont_like_this_child">
                <div class="doesnt_listen"></div>
                <div class="does_drugs"></div>
                <p>Dropped out of school..</p>
            </div>
            <div class="favorite_child">
                <ul>
                    <li>this</li>
                    <li>is</li>
                    <li>a list</li>
                </ul>
            </div>
        </div>
        <ul>
            <li>this</li>
            <li>is</li>
            <li>a list</li>
        </ul>
    </div>

How do I remove div.we_dont_like_this_child with PHP?

What I do know is that I shouldn't use regex because I don't know it that well and will most certainly mess something up.

dbr
  • 1,037
  • 14
  • 34
  • It depends a lot on how general you want your solution to look. You can parse html with the php [`DOMDocument`](http://php.net/manual/en/class.domdocument.php) class. Basically you would iterate over the document and remove nodes with a specific class. – TheGentleman Jan 04 '17 at 18:35
  • I could have bunch of stuff inside `div.we_dont_like_this_child`. I was looking at DOMDocument class but hoped it could be something like `$string->removeHtmlElement('div','class','we_dont_like_this_child')`, guess not. – dbr Jan 04 '17 at 18:41
  • You could write a function like that which used the `DOMDocument` but I'm not aware of anything like that built in. `jQuery` can do it pretty easily if you are open to a front-end solution. – TheGentleman Jan 04 '17 at 18:44
  • Thanks, checking the `DOMDocument` out. Will post when I find solution. `jQuery` is my last resort. – dbr Jan 04 '17 at 18:52
  • JS or Jquery could make this a pretty simple task... What have you tried? – nerdlyist Jan 04 '17 at 19:57
  • jquery will not be a problem `$('.we_dont_like_this_child').remove()`, I'm trying to do this before I save the data to the database. I think I'm close to the solution and I'll post when finished. If you have the working code please do post. – dbr Jan 04 '17 at 20:14
  • If you really want to do it server-side, look into [using XPath to locate the node](http://php.net/manual/en/domxpath.query.php). You can then simply [remove the DOMNode object](http://php.net/manual/en/domnode.removechild.php) from your document. – Bobby Jack Jan 05 '17 at 12:47

0 Answers0