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 Altaf Hussain on 11:17 PM Rating: 5

10 comments:

  1. Thanks! It helps me a lot!

    ReplyDelete
  2. Thanks very much

    ReplyDelete
  3. 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
  4. 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
  5. I am trying this seemingly very easy thing; but nothing happens.

    ReplyDelete

Altaf Web. Powered by Blogger.