tags:

views:

87

answers:

2

Does anybody know if a modified strip_tags function exsists where you can specify the ID of the tags to be stripped, and possbile also specify to remove ALL THE DATA IN THE TAGS. Take for example:

<div id="one">
  <div id="two">
    bla bla bla
  </div>
</div>

Running:


new_strip_tags($data, 'two', true);

Must return:

<div id="one">
</div>

Is there something like this out there?

+5  A: 

You can use DOMDocument and DOMXPath for that.

<?php
$html = '<html><head><title>...</title></head><body>
  <div id="one">
    <div id="two">
      bla bla bla
    </div>
  </div>
</body></html>';

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadhtml($html);

$xpath = new DOMXPath($doc);

$ns = $xpath->query('//div[@id="two"]');
// there can be only one... but anyway
foreach($ns as $node) {
  $node->parentNode->removeChild($node);
}
echo $doc->savehtml();
VolkerK
+1  A: 

That's not exactly what strip_tags does, it strips the tags but leaves the content. What you want is something like this:

function remove_div_with_id($html, $id) {
 return preg_replace('/<div[^>]+id="'.preg_quote($id, '/').'"[^>]*>(.*?)<\/div>/s', '', $html);
}

Note that this will not work correctly with nested tags. If you need that, you might want to use a DOM representation of your HTML.

Alexander Malfait