tags:

views:

73

answers:

2

I need a clean and simple script that can find and remove all event attributes from all html tags in a string. The "on..." attributes that is - onclick, onkeyup etc.

EDIT: Here's how they do it in Kohana:

$string = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $string);

EDIT: Here's how they do it in CodeIgniter:

$string = preg_replace("#<([^><]+?)([^a-z_\-]on\w*|xmlns)(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $string);
+2  A: 

The function takes 4 parameters.

  1. $msg. The text you want to strip attributes from.
  2. $tag. The tag you want to strip attributes from (p, for instance).
  3. $attr. An array with the name of the attributes you want to strip (leaving the rest intact). If the array is empty, the function will strip all attributes.
  4. $suffix. An optional text to append to the tag. It may be a new attribute, for instance.

Taken from Stripping Tag Attributes from HTML code where the author posts the code, I omitted it from my answer since it was lengthy and did not want to claim ownership of the code.

Hope this is what you are looking for.

Anthony Forloney
+1  A: 

You could do something on this line:

<?php

$html = '<p class="foo" onclick="bar()">
    Lorem ipsum dolor sit amet, consectetur <em>adipisicing elit</em>,
    sed do eiusmod tempor incididunt ut labore
    <a href="http://www.google.es" onmouseover="mover()" onmouseout="mout()" title="Google">et dolore magna aliqua</a>.
    t enim ad minim veniam.</p>
';

$doc = new DOMDocument;
$doc->loadHTML($html);

echo "Before:\n" . $doc->saveHTML() . "\n";

foreach($doc->getElementsByTagName('*') as $node){
    $remove = array();
    foreach($node->attributes as $attributeName => $attribute){
        if( substr($attributeName, 0, 2)=='on' ){
            $remove[] = $attributeName;
        }
    }
    foreach($remove as $i){
        $node->removeAttribute($i);
    }
}

echo "After:\n" . $doc->saveHTML() . "\n";

?>

This is a just an idea. It needs some tweaking because it adds tags to convert the HTML fragment in a full document but you can use it as a starting point.

Álvaro G. Vicario