How do I strip only certain HTML tags?

I’m aware of the strip_tags function but wasn’t sure if there was a way to specify which tags to strip. For instance, I only want to strip <p> tags and <font> tags.

You can do it by telling stript_tags to allow certain tags. Ex: strip_tags($text, ‘<p>’) will not strip <p> tags. Unfortunately I do not know of a way to allow you to tell it what tags to strip forcing it to leave the rest alone. You’ll prob need to use regular expressions for that.


To just strip the tags, but not what is in between them you could use something like,

$tags_to_strip = Array("p","font"  );
foreach ($tags_to_strip as $tag)
    $string = preg_replace("/<\\/?" . $tag . "(.|\\s)*?>/",$replace_with,$string);


$string is your text to work on

$replace_with is what you want to replace the tag with.

You can set it to ‘’, to not replace with anything.

Best Regards,

You can also use [fphp]str_replace[/fphp].

$tags = array("<p>", "</p>", "<font>", "</font>");
$string = "<p><font>Hello World of PHP</font></p>";
echo str_replace($tags, "", $string);


this might be useful for you.

You could also use some regexp like this one:

That should strip <font>; </font>; <p>; </p>; <div>; </div>; but also <font color=“#FF0000”> and things like that. And all of that with only one expression. :wink: