note 86463 deleted from function.strip-tags by aharvey
| From: | aharvey@php.net | Date: | Thu, 20 Sep 2012 12:06:03 +0000 |
| Subject: | note 86463 deleted from function.strip-tags by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190913@lists.php.net to get a copy of this message | ||
Note Submitter: lucky760 at VideoSift dot com
----
It's come to my attention that PHP's strip_tags has been doing something funky to some
video embed codes that our members submit. I'm not sure the exact situation, but whenever there
is a <param> tag that is very long, strip_tags() will completely remove the tag even though
it's specified as an allowable tag.
Here's an example of the existing problem:
<?php
// a single very long <param> tag
$html =<<<EOF
<param name="flashVars" value="skin=http%3A//cdn-i.dmdentertainm
...[snip]...
vie%20of%20All-Time"/>
EOF;
echo strip_tags($html, '<param>');
// this outputs an empty string
?>
This is the function I built to fix and extend the functionality of strip_tags(). The args are:
- $i_html - the HTML string to be parsed
- $i_allowedtags - an array of allowed tag names
- $i_trimtext - whether or not to strip all text outside of the allowed tags
<?php
function real_strip_tags($i_html, $i_allowedtags = array(), $i_trimtext = FALSE) {
if (!is_array($i_allowedtags))
$i_allowedtags = !empty($i_allowedtags) ? array($i_allowedtags) : array();
$tags = implode('|', $i_allowedtags);
if (empty($tags))
$tags = '[a-z]+';
preg_match_all('@</?\s*(' . $tags .
')(\s+[a-z_]+=(\'[^\']+\'|"[^"]+"))*\s*/?>@i', $i_html,
$matches);
$full_tags = $matches[0];
$tag_names = $matches[1];
foreach ($full_tags as $i => $full_tag) {
if (!in_array($tag_names[$i], $i_allowedtags))
if ($i_trimtext)
unset($full_tags[$i]);
else
$i_html = str_replace($full_tag, '', $i_html);
}
return $i_trimtext ? implode('', $full_tags) : $i_html;
}
?>
And here's an example with the a block of full video embed code with
<object><embed><param> and some extraneous HTML:
<?php
$html =<<<EOF
<em><div><object type="application/x-shock
...[snip]...
me.html">Wal-Mart Makes The Worst Movie of All-Time</a> -- powered by
whatever</div></em>
EOF;
$good_html = real_strip_tags($html, array('object', 'embed', 'param'),
TRUE);
?>
Now $good_html contains only the specified tags and none of the "powered by" type text. I
hope someone finds this as useful as I needed it to be. :)