How to strip a tag and all of its inner html using the tag's id?

Viewed 57134

I have the following html:

<html>
 <body>
 bla bla bla bla
  <div id="myDiv"> 
         more text
      <div id="anotherDiv">
           And even more text
      </div>
  </div>

  bla bla bla
 </body>
</html>

I want to remove everything starting from <div id="anotherDiv"> until its closing <div>. How do I do that?

7 Answers

Following RafaSashi's answer using preg_replace(), here's a version that works for a single tag or an array of tags:

/**
 * @param $str string
 * @param $tags string | array
 * @return string
 */

function strip_specific_tags ($str, $tags) {
  if (!is_array($tags)) { $tags = array($tags); }

  foreach ($tags as $tag) {
    $_str = preg_replace('/<\/' . $tag . '>/i', '', $str);
    if ($_str != $str) {
      $str = preg_replace('/<' . $tag . '[^>]*>/i', '', $_str);
    }
  }
  return $str;
}
Related