note 102620 modified in function.strip-tags by danbrown

From: Date: Thu, 24 Feb 2011 21:15:58 +0000
Subject: note 102620 modified in function.strip-tags by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177305@lists.php.net to get a copy of this message
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 &quot; and &#39;. <?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} == '"' ? '&quot;' : '&#39;'); // 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. --was-- 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 &quot; and &#39;. 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} == '"' ? '&quot;' : '&#39;'); // 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. http://php.net/manual/en/function.strip-tags.php

« previous php.notes (#177305) next »