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
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.
Call function like this :
$result = strip_single('a',$string);
It will remove all <a> tags from string.
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
Reviewed by JS Pixels
on
December 08, 2011
Rating:
Thanks! It helps me a lot!
ReplyDeleteGreat code mate! Thanks a lot!
ReplyDeleteThanks alot
ReplyDeleteThis 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
ReplyDeleteGreat. Thank you.
ReplyDeleteit workds
ReplyDeletefunction strip_html($tags, $string){
ReplyDeleteforeach($tags as $tag) $string = preg_replace(array('/(<'.$tag.'\\b[^>]*>)|(<\/'.$tag.'>)/i'), '', $string);
return $string;
}
strip_html(array('iframe', 'frame'), $html);
I am trying this seemingly very easy thing; but nothing happens.
ReplyDelete