Dec
01
2009

Using PHP to Remove an HTML Tag from a String

by   |  Posted in Tutorials  |  2 comments

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.

<?php
$string = 'Here is your content with an image tag <img src="http://bavotasan.com/wp-content/themes/bavotasan_new/images/bavota.png" alt="Image" />' ;
$string = preg_replace("/<img[^>]+\>/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.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , ,

Short URL: http://bit.ly/dedSFn

Discussion 2 Comments

  1. horaire de priere on February 24, 2010 at 7:42 pm

    Great code, thanks for sharing it !

    Fredj from Paris

  2. bineet on May 11, 2010 at 6:56 am

    thanks .i need this code for our wordpress project