Falls das mal jemand für eine Website, ein CMS oder ähnliches gebrauchen kann: Folgende Regular-Expression filtert Eventhandler (onclick, onmouseover usw.) automatisch aus HTML Elementen aus, da diese ein Sicherheitsrisiko (XSS) darstellen.
Die Funktion nimmt als Parameter einen String mit dem zu filternden Inhalt oder ein Array aus Strings an.
[geshi lang=php ln=y]function stripEvents ($myVar) {
if (is_array($myVar)) {
foreach ($myVar as $k => $v)
$myVar[$k] = stripEvents($v);
return $myVar;
}
else {
// First we loop through all tags that contain possible event handler.
// To avoid endless loops (could happen if the first preg_match detects a possible
// event handler, which in fact isn’t one and won’t be filtered by the second one), we
// store the position where the first match occurs. If we get to this point again, we know
// that we are beginning an endless loop and can escape from it.
$lowestOffset = 0;
while(preg_match(“/<[^<]*?\son[^<]*?>/i”, $myVar, $tag, PREG_OFFSET_CAPTURE) != 0) {
if($lowestOffset < $tag[0][1])
break;
else {
$lowestOffset = $tag[0][1];
}
// To rebuild the string without the eventhandler, we have to store the length of the tag
// The offset where this tag begins is stored in $tag[0][1]
$length = strlen($tag[0][0]);
// Now strip out the event handler
$tagStripped = preg_replace("/(\s)+on\w+\s*?=\s*?[\"'].*?[\"'](\s|>)+?/i”, ‘$1$2′, $tag[0][0]);
// Split the complete source string into 2 parts without the modified HTML tag
$part1 = substr($myVar, 0, $tag[0][1]);
$part2 = substr($myVar, $tag[0][1]+$length);
// Rebuild the source string containing the modified, event-handler-free HTML tag
$myVar = $part1 . $tagStripped . $part2;
}
}
return $myVar;
}[/geshi]
//Update (05.12.2006 – 09.24 Uhr): Hab die Funktion nochmals überarbeitet, da es teilweise durch greedy RegExes zu fehlerhaften Matches kommt, dem wird jetzt entgegengewirkt, indem zuerst alle Tags gesucht werden, welche überhaupt als möglicher Container eines Eventhandlers in Frage kommen und dann einzeln gefiltert werden.










