How to remove div by class php. Remove div & div contents

This article was written by in August 16, 2014, & may not be posted on other sites!
Original source url for this article: How to remove div by class php. Remove div & div contents

How to remove div by class php. Remove div and div contents.
If you need to remove a div by class or ID, and the divs contents, PHP function preg_replace  and regEx will do the job. Remove any html element, this is how to:

 

How to remove div and div contents by class in php using preg_replace & regEx

RegEx, or regular expressions is code for what you would like to remove, and PHP function preg_replace() will remove all div or divs matching, or replacing them with something else. In the examples below, $incoming_data is where you put all your content before removing elements, and $result is the final product. Basically we are telling the code to find all divs with class=”myclass”  and replace them with ” ” (nothing).

How to remove a div and its contents by class in PHP
Just change “myclass” to whatever class your div has.
$result = preg_replace('#<div class="myclass">(.*?)</div>#', ' ', $incoming_data);

How to remove a div and its contents by ID in PHP
Just change “myid” to whatever ID your div has.
$result = preg_replace('#<div id="myid">(.*?)</div>#', ' ', $incoming_data);

If your div has multiple classes?
Just change “myid” to whatever ID your div has like this.
$result = preg_replace('#<div id="myid(.*?)</div>#', ' ', $incoming_data);
or if div don’t have an ID, filter on the first class of the div like this.
$result = preg_replace('#<div class="myclass(.*?)</div>#', ' ', $incoming_data);

How to remove all headings <h1> in PHP
This is how to remove all <h1> headings.
$result = preg_replace('#<h1>(.*?)</h1>#', ' ', $incoming_data);
and if the heading have a class, do something like this:
$result = preg_replace('#<h1 class="myclass">(.*?)</h1>#', ' ', $incoming_data);

 

Spread the word

Facebooktwittergoogle_pluslinkedinmail

One thought on “How to remove div by class php. Remove div & div contents

  1. Valentin

    Great post! Thanks for sharing 🙂

    What about switching a bootstrap 2 class for the bootstrap 3 ones?

    For example, going from:

    to:

    *Only affecting the content inside the class attribute.

Leave a Reply

Your email address will not be published. Required fields are marked *