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); 

      

thank

+3


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>
</div>
<div class=...>

      

+6


source


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



+3


source


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;
$doc->loadHTML($html);
$headerElement = $doc->getElementById('header');
$headerElement->parentNode->removeChild($headerElement);
$amendedHtml = $doc->saveHTML(); 

      

+1


source


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

      

delete everything

<div...>
</div>
<b....>
</b>
<span...>
</span>

      

0


source







All Articles