note 105589 deleted from function.strip-tags by danbrown
| From: | danbrown@php.net | Date: | Tue, 30 Aug 2011 17:12:56 +0000 |
| Subject: | note 105589 deleted from function.strip-tags by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182828@lists.php.net to get a copy of this message | ||
Note Submitter: oldmanbim at gmail dot com
----
phpjs.org has a better version of strip_tags. I've taken their javascript and translated it to
PHP:
function my_strip_tags ($input, $allowed) {
// Strips HTML and PHP tags from a string
//
// version: 1107.2516
// discuss at: http://phpjs.org/functions/strip_tags
// + original by: Kevin van Zonneveld
// + improved by: Luke Godfrey
// + input by: Pul
// + bugfixed by: Kevin van Zonneveld
// + bugfixed by: Onno Marsman
// + input by: Alex
// + bugfixed by: Kevin van Zonneveld
// + input by: Marc Palau
// + improved by: Kevin van Zonneveld
// + input by: Brett Zamir
// + bugfixed by: Kevin van Zonneveld
// + bugfixed by: Eric Nagel
// + input by: Bobby Drake
// + bugfixed by: Kevin van Zonneveld
// + bugfixed by: Tomasz Wesolowski
// + input by: Evertjan Garretsen
// + revised by: RafaÅ Kukawski
// * example 1: strip_tags('<p>Kevin</p> <b>van</b>
<i>Zonneveld</i>', '<i><b>');
// * returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// * example 2: strip_tags('<p>Kevin <img src="someimage.png"
onmouseover="someFunction()">van <i>Zonneveld</i></p>',
'<p>');
// * returns 2: '<p>Kevin van Zonneveld</p>'
// * example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van
Zonneveld</a>", "<a>");
// * returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van
Zonneveld</a>'
// * example 4: strip_tags('1 < 5 5 > 1');
// * returns 4: '1 < 5 5 > 1'
// * example 5: strip_tags('1 <br/> 1');
// * returns 5: '1 1'
// * example 6: strip_tags('1 <br/> 1', '<br>');
// * returns 6: '1 1'
// * example 7: strip_tags('1 <br/> 1', '<br><br/>');
// * returns 7: '1 <br/> 1'
// making sure the $allowed arg is a string containing only tags in lowercase
(<a><b><c>)
$allowed = preg_match_all('/<[a-z][a-z0-9]*>/', $allowed, $matches);
$allowed = implode('', $matches[0]);
// Get rid of comments and php tags
$commentsAndPhpTags = '/<!--[\\s\\S]*?-->|<\\?(?:php)?[\\s\\S]*?\?>/';
$input = preg_replace($commentsAndPhpTags, '', $input);
// Get rid of all but allowed HTML tags
$tags = '/<\\/?([a-z][a-z0-9]*)\\b[^>]*>/';
$input = preg_replace_callback($tags, create_function('$matches', 'return
(strpos("' . $allowed .'", "<{$matches[1]}>")===FALSE) ?
"" : $matches[0];'), $input);
return $input;
}