note 91498 modified in function.strip-tags by danbrown

From: Date: Wed, 09 Sep 2009 14:15:40 +0000
Subject: note 91498 modified in function.strip-tags by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160353@lists.php.net to get a copy of this message
Wanted a function to do what nick's was supposed to do: "strip tags and attributes, but with allowable attributes." but I couldn't get his to work properly, I think it had something to do with greedy / non greedy searching. Anyway, I modified his a bit: <?php function strip_tags_attributes($string,$allowtags=NULL,$allowattributes=NULL){ $string = strip_tags($string,$allowtags); if (!is_null($allowattributes)) { if(!is_array($allowattributes)) $allowattributes = explode(",",$allowattributes); if(is_array($allowattributes)) $allowattributes = implode(")(?<!",$allowattributes); if (strlen($allowattributes) > 0) $allowattributes = "(?<!".$allowattributes.")"; $string = preg_replace_callback("/<[^>]*>/i",create_function( '$matches', 'return preg_replace("/ [^ =]*'.$allowattributes.'=(\"[^\"]*\"|\'[^\']*\')/i", "", $matches[0]);' ),$string); } return $string; } ?> [EDIT BY danbrown AT php DOT net: Original function by (nick AT optixsolutions DOT co DOT uk) on 31-MAR-09 with the following note:] Function to strip tags and attributes, but with allowable attributes. Usage: Allowable attributes can be comma seperated or array Example: <?php strip_tags_attributes($string,'<strong><em><a>','href,rel'); ?> --was-- Wanted a function to do what nick's was supposed to do: "strip tags and attributes, but with allowable attributes." but I couldn't get his to work properly, I think it had something to do with greedy / non greedy searching. Anyway, I modified his a bit: <?php function strip_tags_attributes($string,$allowtags=NULL,$allowattributes=NULL){ $string = strip_tags($string,$allowtags); if (!is_null($allowattributes)) { if(!is_array($allowattributes)) $allowattributes = explode(",",$allowattributes); if(is_array($allowattributes)) $allowattributes = implode(")(?<!",$allowattributes); if (strlen($allowattributes) > 0) $allowattributes = "(?<!".$allowattributes.")"; $string = preg_replace_callback("/<[^>]*>/i",create_function( '$matches', 'return preg_replace("/ [^ =]*'.$allowattributes.'=(\"[^\"]*\"|\'[^\']*\')/i", "", $matches[0]);' ),$string); } return $string; } ?> http://php.net/manual/en/function.strip-tags.php

« previous php.notes (#160353) next »