Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove </div> HTML tag from a string in PHP

Tags:

regex

php

According to the post here, the code below can remove the HTML tag, such as <div>. But I found that the end tag </div> still remain in the string.

$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 work, how can I fix this issue?

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

Thanks

like image 668
Charles Yeung Avatar asked Sep 18 '25 09:09

Charles Yeung


2 Answers

The end tag doesn't have anything between the div and the >, so instead try something like:

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

This will remove patterns of the form:

<div>
</div>
<div class=...>
like image 193
Rowland Shaw Avatar answered Sep 20 '25 23:09

Rowland Shaw


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

like image 22
Desolator Avatar answered Sep 21 '25 00:09

Desolator