0

Is there a way in PHP to remove all divs with a specific class from a content and return a result, for example I have this code :

<?php
$content = '<div class="toRemove">
content here 
bla bla
<div class="toBeRemoved">content here also</div>
<div class="test">content ...</div>
lorem ipsum dolor sit ...
other divs here with different classes and ids
</div>
<div class="otherInfo">....</div>
';
$content = preg_replace('#<div class="toRemove">([\s\S]*?)</div>#','', $content); // tried this but did work as I wanted to
echo $content;

What I want is to remove all content inside div with class toRemove, what I get is a content where child divs not removed !

Thanks in advance for ur help.

Hanane
  • 345
  • 1
  • 8
  • 19
  • 1
    You shall not try to parse semantics of html with regex. Regex is NOT intended for editing semantic markup. In this example, besides the fact that it does not do what you intend it to do, it deletes everyhting between the first and the fourth line of your html. Hereby it is deleting two opening but only one closing tag, which results in broken html. Give https://tommcfarlin.com/manipulate-the-dom-using-php/ a read, it should give you the direction in which you should go to do it properly (although it does not show exactly how to solve this specific problem it's a good starting point) – Dennis Richter Apr 21 '20 at 10:01
  • 1
    You are right , I didn't pay attention to the tag that wasn't removed. thanks for the link I will check to have more info – Hanane Apr 21 '20 at 10:22

0 Answers0