Remove HTML </div> tag from string in PHP

According to the post here , the code below can remove the HTML tag for example <div>

. But I found that the end tag </div>

still stays on the line.

$content = "<div id=\"header\">this is something with an <img src=\"test.png\"/> in it.</div>";
$content = preg_replace("/<div[^>]+\>/i", "", $content); 
echo $content;


I have tried something below but still not working, how can I fix this problem?

$content = preg_replace("/<\/div[^>]+\>/i", "", $content); 
$content = preg_replace("/<(/)div[^>]+\>/i", "", $content); 




source to share

4 answers

The end tag has nothing between the div and >

, so try something like:

$content = preg_replace("/<\/?div[^>]*\>/i", "", $content); 


This will remove the form templates:

<div class=...>




change it to "/<[\/]*div[^>]*>/i"



If you can guarantee that the HTML being passed in will be correct and structured in a specific way, you should be fine with a regexp.

In general, however, it's best to avoid using regular expressions to work with HTML, because the markup can be so varied and messy. Try using a library like DOMDocument instead - it handles all the clutter for you.

With DOMDocument, you would do something like:

$doc = new DOMDocument;
$headerElement = $doc->getElementById('header');
$amendedHtml = $doc->saveHTML(); 




$content = preg_replace("/<\/?(div|b|span)[^>]*\>/i", "", $content); 


delete everything





All Articles