PHP Regular Expression to Remove A Tag

I needed to remove a tag and all the text within a tag. Sounds easy enough. Here is the HTML:

$content = 'Hello <div id="tag_to_remove">I would like everything within these div tags to be removed!</div> World';
echo $content;

The desired results:

Hello World

Here is the PHP to remove the tag and all text within the tag:

$content = 'Hello <div id="tag_to_remove">I would like everything within these div tags to be removed!</div> World';
echo preg_replace('/<div id=\"tag_to_remove[\\d\\D]*?\/div>/','',$content);

The end results:

Hello World

 

Leave a Reply