note 71265 deleted from function.preg-replace by tularis
| From: | tularis@php.net | Date: | Mon, 20 Nov 2006 12:39:56 +0000 |
| Subject: | note 71265 deleted from function.preg-replace by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-119897@lists.php.net to get a copy of this message | ||
Note Submitter: theppg_001 at hotmail dot com
----
Hi there
This was originally made by someone eles but it didn't work correctly and so I remade it and as
far as I know it works right.
<?php
/**
* strip_selected_tags ( string str [, string strip_tags[, strip_content flag]] )
* ---------------------------------------------------------------------
* Like strip_tags() but inverse; the strip_tags tags will be stripped, not kept.
* strip_tags: string with tags to strip, ex: "<a><p><quote>" etc.
* strip_content flag: TRUE will also strip everything between open and closed tag
*/
function strip_selected_tags($str, $tags = "", $stripContent = false)
{
preg_match_all("/<([^>]+)>/i", $tags, $allTags, PREG_PATTERN_ORDER);
$replace = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
foreach ($allTags[1] as $tag) {
if ($stripContent) {
$str = preg_replace($replace,'',$str);
}
$str = preg_replace($replace,'${2}',$str);
}
return $str;
}
?>
Before I 'fixed' it, when running
strip_selected_tags("this is <p align=\"center\">a test</p> and
<b>this is bold</b>","<p><b>")
You would get back
"this is <p align=\"center\">a test</p> and this is bold"
Why? Because it did not take into account that there could be options etc in the HTML Tag.
My one works perfectly when stripping just the tags or the tag and its contents too!
So now when you run
strip_selected_tags("this is <p align=\"center\">a test</p> and
<b>this is bold</b>","<p><b>")
You get back
"this is a test and this is bold"
Or when running
strip_selected_tags("this is <p align=\"center\">a test</p> and
<b>this is bold</b>","<p><b>",true)
You get back
"this is and "
Hope it helps someone :)