Strip an entire block of html based on class or id with php
<p>I have the following php function which is supposed to remove a block of html tag based on a given classname or id. I got this function at <a href="http://www.katcode.com/php-html-parsing-extracting-and-removing-html-tag-of-specific-class-from-string/" rel="nofollow">http://www.katcode.com/php-html-parsing-extracting-and-removing-html-tag-of-specific-class-from-string/</a></p>

<p>This function works as it should but seems to have problems when we have nested tags. In the example below i'm trying to remove the entire div block that has class 'two'.</p>

<p>This function seems to have problems with nested tags. It's not removing the div block properly. It's having problems figuring out beginning and end of the block. How can i rework this function remove an entire tag regardless of how many nested elements it contains. I'm open to other php suggestions. I can easily do this with jQuery, but i'm looking for a php server side solution. </p>

<p><strong>html looks like this</strong></p>

<pre><code>&lt;div class="test"&gt;
    &lt;div&gt;testing1&lt;/div&gt;
    &lt;div class="two"&gt;
        &lt;div&gt;testing3&lt;/div&gt;
        &lt;div&gt;testing3&lt;/div&gt;
    &lt;/div&gt;
    &lt;div&gt;testing3&lt;/div&gt;
    &lt;div&gt;testing4&lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p><strong>php</strong></p>

<pre><code>&lt;?php
$x = '&lt;div class="test"&gt;&lt;div&gt;testing1&lt;/div&gt;&lt;div class="two"&gt;&lt;div&gt;testing3&lt;/div&gt;&lt;div&gt;testing3&lt;/div&gt;&lt;/div&gt;&lt;div&gt;testing3&lt;/div&gt;&lt;div&gt;testing4&lt;/div&gt;&lt;/div&gt;';

    function removeTag($str,$id,$start_tag,$end_tag){
            while(($pos_srch = strpos($str,$id))!==false){
                $beg = substr($str,0,$pos_srch);
                $pos_start_tag = strrpos($beg,$start_tag);
                $beg = substr($beg,0,$pos_start_tag);
                $end = substr($str,$pos_srch);
                $end_tag_len = strlen($end_tag);
                $pos_end_tag = strpos($end,$end_tag);
                $end = substr($end,$pos_end_tag+$end_tag_len);
                $str = $beg.$end;
            }
            return $str;
    }

echo removeTag($x,'two','&lt;div','/div&gt;');
?&gt;
</code></pre>
