Using PHP to Remove an HTML Tag from a String

There are times when you need to strip one specific HTML tag from a string and the PHP function strip_tags() doesn’t work the way you want it to. strip_tags() allows for certain exclusions, but why would you use that when you only want to exclude one tag and include all other tags? Especially when you can use preg_replace().

Here is a quick little piece of code that can be modified for any specific HTML tag you want to remove from a string. I am using it below to remove an image tag.

' ;
$string = preg_replace("/]+\>/i", "", $string);
echo $string // will output "Here is your content with an image tag" without the image tag
?>

You can replace the img in the preg_replace() function for it to work with whichever HTML tag you wish.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie