note 102620 deleted from function.strip-tags by aharvey
| From: | aharvey@php.net | Date: | Thu, 20 Sep 2012 12:14:25 +0000 |
| Subject: | note 102620 deleted from function.strip-tags by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190925@lists.php.net to get a copy of this message | ||
Note Submitter: aleksey at favor dot com dot ua
----
strip_tags destroys the whole HTML behind the tags with invalid attributes. Like <img
src="/images/image.jpg""> (look, there is an odd quote before >.)
So I wrote function which fixes unsafe attributes and replaces odd " and ' quotes with
" and '.
<?php
function fix_unsafe_attributes($s) {
$out = false;
while (preg_match('/<([A-Za-z])[^>]*?>/', $s, $i, PREG_OFFSET_CAPTURE)) { //
find where the tag begins
$i = $i[1][1]+1;
$out.= substr($s, 0, $i);
$s = substr($s, $i);
// scan attributes and find odd " and '
while (((($i1 = strpos($s, '"')) || 1) && (($i2 = strpos($s,
'\'')) || 1)) && ($i1 !== false || $i2 !== false) &&
(($i = (int)(($i1 !== false) && ($i2 !== false) ? ($i1 < $i2 ? $i1 : $i2) :
($i1 == false ? $i2 : $i1))) !== false) &&
((($c = strpos($s, '>')) === false) || ($i < $c))) {
$c = $s{$i};
if (($i < 1) || ($s{$i-1} != '=')) {
$out.= substr($s, 0, $i).($s{$i} == '"' ? '"' :
'''); // replace odd " and '
$s = substr($s, $i+1);
}else {
$i++;
$out.= substr($s, 0, $i);
$s = substr($s, $i);
if (($i = strpos($s, $c)) !== false) {
$i++;
$out.= substr($s, 0, $i);
$s = substr($s, $i);
}
}
}
}
return $out.$s;
}
?>
Maybe this function can be rewritten with simple regular expression but I have no luck to make it
quickly.