note 89967 modified in function.strip-tags by danbrown
| From: | danbrown@php.net | Date: | Tue, 31 Mar 2009 18:05:14 +0000 |
| Subject: | note 89967 modified in function.strip-tags by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-152657@lists.php.net to get a copy of this message | ||
Function to strip tags and attributes, but with allowable attributes.
<?php
function strip_tags_attributes($string,$allowtags=NULL,$allowattributes=NULL){
if($allowattributes){
if(!is_array($allowattributes))
$allowattributes = explode(",",$allowattributes);
if(is_array($allowattributes))
$allowattributes = implode("|",$allowattributes);
$rep = '/([^>]*)
('.$allowattributes.')(=)(\'.*\'|".*")/i';
$string = preg_replace($rep, '$1 $2_-_-$4', $string);
}
if(preg_match('/([^>]*) (.*)(=\'.*\'|=".*")(.*)/i',$string) >
0){
$string = preg_replace('/([^>]*) (.*)(=\'.*\'|=".*")(.*)/i',
'$1$4', $string);
}
$rep = '/([^>]*)
('.$allowattributes.')(_-_-)(\'.*\'|".*")/i';
if($allowattributes)
$string = preg_replace($rep, '$1 $2=$4', $string);
return strip_tags($string,$allowtags);
}
?>
Usage:
Allowable attributes can be comma seperated or array
Example:
<?php
strip_tags_attributes($string,'<strong><em><a>','href,rel');
?>
--was--
An improvement on my previous strip tags/attributes (with allowable tags/attributes) function (it
broke if there were no attributes in the code):
function strip_tags_attributes($string,$allowtags=NULL,$allowattributes=NULL){
if($allowattributes){
if(!is_array($allowattributes))
$allowattributes = explode(",",$allowattributes);
if(is_array($allowattributes))
$allowattributes = implode("|",$allowattributes);
$rep = '/([^>]*)
('.$allowattributes.')(=)(\'.*\'|".*")/i';
$string = preg_replace($rep, '$1 $2_-_-$4', $string);
}
if(preg_match('/([^>]*) (.*)(=\'.*\'|=".*")(.*)/i',$string) >
0){
$string = preg_replace('/([^>]*) (.*)(=\'.*\'|=".*")(.*)/i',
'$1$4', $string);
}
$rep = '/([^>]*)
('.$allowattributes.')(_-_-)(\'.*\'|".*")/i';
if($allowattributes)
$string = preg_replace($rep, '$1 $2=$4', $string);
return strip_tags($string,$allowtags);
}
http://php.net/manual/en/function.strip-tags.php