Remove a specific tag from php string

Sometimes we come to the situation when we need to strip one specific HTML tag from a string and the PHP function strip_tags() doesn’t work the way we want it to.

strip_tags() allows for certain exclusions, but why would we use that when we only want to exclude one tag and include all other tags? Especially when we can use preg_replace().

Here is a quick little function. It takes two parameters, the tag to be removed and the string from which it is to be removed.

  function strip_single($tag,$string){
    $string=preg_replace('/<'.$tag.'[^>]*>/i', '', $string);
    $string=preg_replace('/<\/'.$tag.'>/i', '', $string);
    return $string;
  } 


Call function like this :

$result = strip_single('a',$string);

It will remove all <a> tags from string.
Remove a specific tag from php string Remove a specific tag from php string Reviewed by JS Pixels on December 08, 2011 Rating: 5

8 comments:

  1. Thanks! It helps me a lot!

    ReplyDelete
  2. This is not good. If you pass, e.g., $result = strip_single('s',$string); (to strip all s tags), it also strips all span tags too

    ReplyDelete
  3. function strip_html($tags, $string){
    foreach($tags as $tag) $string = preg_replace(array('/(<'.$tag.'\\b[^>]*>)|(<\/'.$tag.'>)/i'), '', $string);
    return $string;
    }

    strip_html(array('iframe', 'frame'), $html);

    ReplyDelete
  4. I am trying this seemingly very easy thing; but nothing happens.

    ReplyDelete

Altaf Web. Powered by Blogger.