note 116108 added to function.strip-tags
| From: | fernando at zauber dot es | Date: | Mon, 10 Nov 2014 23:45:35 +0000 |
| Subject: | note 116108 added to function.strip-tags | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-200866@lists.php.net to get a copy of this message | ||
As you probably know, the native function strip_tags don't work very well with malformed HTML
when you use the allowed tags parameter.
This is a very simple but effective function to remove html tags. It takes a list (array) of allowed
tags as second parameter:
<?php
function flame_strip_tags($html, $allowed_tags=array()) {
$allowed_tags=array_map(strtolower,$allowed_tags);
$rhtml=preg_replace_callback('/<\/?([^>\s]+)[^>]*>/i', function ($matches)
use (&$allowed_tags) {
return in_array(strtolower($matches[1]),$allowed_tags)?$matches[0]:'';
},$html);
return $rhtml;
}
?>
The function works reasonably well with invalid/bad formatted HTML.
Use:
<?php
$allowed_tags=array("h1","a");
$html=<<<EOD
<h1>Example</h1>
<dt><a href='/manual/en/getting-started.php'>Getting
Started</a></dt>
<dd><a href='/manual/en/introduction.php'>Introduction</a></dd>
<dd><a href='/manual/en/tutorial.php'>A simple tutorial</a></dd>
<dt><a href='/manual/en/langref.php'>Language Reference</a></dt>
<dd><a href='/manual/en/language.basic-syntax.php'>Basic
syntax</a></dd>
<dd><a href='/manual/en/reserved.interfaces.php'>Predefined Interfaces and
Classes</a></dd>
</dl>
EOD;
echo flame_strip_tags($html,$allowed_tags);
?>
The output will be:
<h1>Example</h1>
<a href='/manual/en/getting-started.php'>Getting Started</a>
<a href='/manual/en/introduction.php'>Introduction</a>
<a href='/manual/en/tutorial.php'>A simple tutorial</a>
<a href='/manual/en/langref.php'>Language Reference</a>
<a href='/manual/en/language.basic-syntax.php'>Basic syntax</a>
<a href='/manual/en/reserved.interfaces.php'>Predefined Interfaces and
Classes</a>
----
Server IP: 72.52.91.14
Probable Submitter: 92.57.76.49
----
Manual Page -- http://php.net/manual/en/function.strip-tags.php
Edit -- https://master.php.net/note/edit/116108
Del: integrated -- https://master.php.net/note/delete/116108/integrated
Del: useless -- https://master.php.net/note/delete/116108/useless
Del: bad code -- https://master.php.net/note/delete/116108/bad+code
Del: spam -- https://master.php.net/note/delete/116108/spam
Del: non-english -- https://master.php.net/note/delete/116108/non-english
Del: in docs -- https://master.php.net/note/delete/116108/in+docs
Del: other reasons-- https://master.php.net/note/delete/116108
Reject -- https://master.php.net/note/reject/116108
Search -- https://master.php.net/manage/user-notes.php