05May2011
Author
Dave
Category
PHP
Tags
, ,
Strip tags from a string Thumbnail

Strip tags from a string

From time to time you may need to remove certain tags from a string but leave other tags in tact, This tutorial will show you how to accomplish this.

From time to time you may need to remove certain tags from a string but leave other tags in tact, This tutorial will show you how to accomplish this.

You can use strip_tags() to remove all tags or specify which tags are allowed generally this is fine but what if you have a lot of different tags that you want to leave alone and only remove a one or more tags using strip_tags() you would need to specify every single tag you want to allow which can get very tiresome, a much better approach would be if you could simple say remove only the tags you specify.

There is no such function built into PHP to do that but making your own function to do this is thankfully very simple. All that needs to be passed to the function is the string and the tags you want to remove:

strip_only($str, '<br /><hr />');

The function scans all the tags in the string and if found removes them this is all done is a loop then once finished returns the string.

function strip_only($str, $tags) {
 
if(!is_array($tags)) {
 
$tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
 
if(end($tags) == '') array_pop($tags);
 
}
 
foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
 
return $str;
 
}
Author
Dave

About the Author

has written 72 articles on Dave is my name.

My name is David Carr I'm a PHP web developer based in Hull it is my passion to design and develop clean, accessible and usable websites using PHP and other web technologies, I'm an avid Twitter user why not follow me? https://twitter.com/daveismynamecom

Visit this author's website   ·   View more posts by

Sharing is caring.
  • Subscribe to our feed
  • Share this post on Delicious
  • StumbleUpon this post
  • Share this post on Digg
  • Tweet about this post
  • Share this post on Mixx
  • Share this post on Technorati
  • Share this post on Facebook
  • Share this post on NewsVine
  • Share this post on Reddit
  • Share this post on Google
  • Share this post on LinkedIn

Discussion

2 responses to "Strip tags from a string"

  • Richard says:

    Nice PHP script -thanks.
    I cannot yet get it to remove CSS eg

    #header h1 a {
    display: block;
    width: 300px;
    height: 80px;
    }

    strip_only($str, '');

    not doing it! Any ideas?

Leave a Comment