简体   繁体   中英

Remove on* JS event attributes from HTML tags

Please, help to parse in PHP simple html strings (php regexp). I need drop html-js events from html code. I know php regular expressions very bad.

Examples of code:

<button onclick="..javascript instruction..">

Result: <button>

<button onclick="..javascript instruction.." value="..">

Result: <button value="..">

<button onclick=..javascript instruction..>

Result: <button>

<button onclick=..javascript instruction.. value>

Result: <button value>

I need to do this without quotes and with, because all modern browsers is allow to do attributes without quoutes.

Note: I nedd parse not only onclick.. it is all atrributes, which begins from 'on'.

Note (2): DONT TRY TO ADVICE HTML PARSER, BECAUSE IT WILL BE VERY BIG DOM TREE FOR PARSE..

UPDATED : Thanks, for your reply! Now, i use HTMLPurifier component on written by me a small framework.

There is nothing wrong with tokenizing with regex. But making a full HTML tokenizer with regex is a lot of work and difficult to get right. I would recommend using a proper parser, because you will probably need to remove script tags and such anyway.

Assuming a full tokenizer is not needed, the following regex and code can be used to remove on* attributes from HTML tags. Because a proper tokenizer is not used, it would match strings that look like tags even in scripts, comments, CDATA, etc.

There is no guarantee that all event attributes will be removed for all input/browser combinations! See the notes below.


Note on error tolerance :

Browsers are usually forgiving of errors. Due to that it is difficult to tokenize tags and get the attributes as the browser would see them when "invalid" data is present. Because error tolerance and handling differs between browsers it is impossible to make a solution that works for them all in all cases.

Thus : Some browser(s) (current, past, or future version) could treat something which my code does not think is a tag, as a tag, and execute the JS code.

In my code I have attempted to mimic tokenization of tags (and error tolerance/handling) of recent Google Chrome versions. Firefox seems to do it in a similar way.

IE 7 differs, in some cases it's not as tolerant (which is better than if it was more tolerant). (IE 6 - lets not go there. See XSS Filter Evasion Cheat Sheet )


Relevant links:


The code

$redefs = '(?(DEFINE)
    (?<tagname> [a-z][^\s>/]*+    )
    (?<attname> [^\s>/][^\s=>/]*+    )  # first char can be pretty much anything, including =
    (?<attval>  (?>
                    "[^"]*+" |
                    \'[^\']*+\' |
                    [^\s>]*+            # unquoted values can contain quotes, = and /
                )
    ) 
    (?<attrib>  (?&attname)
                (?: \s*+
                    = \s*+
                    (?&attval)
                )?+
    )
    (?<crap>    [^\s>]    )             # most crap inside tag is ignored, will eat the last / in self closing tags
    (?<tag>     <(?&tagname)
                (?: \s*+                # spaces between attributes not required: <b/foo=">"style=color:red>bold red text</b>
                    (?>
                        (?&attrib) |    # order matters
                        (?&crap)        # if not an attribute, eat the crap
                    )
                )*+
                \s*+ /?+
                \s*+ >
    )
)';


// removes onanything attributes from all matched HTML tags
function remove_event_attributes($html){
    global $redefs;
    $re = '(?&tag)' . $redefs;
    return preg_replace("~$re~xie", 'remove_event_attributes_from_tag("$0")', $html);
}

// removes onanything attributes from a single opening tag
function remove_event_attributes_from_tag($tag){
    global $redefs;
    $re = '( ^ <(?&tagname) ) | \G \s*+ (?> ((?&attrib)) | ((?&crap)) )' . $redefs;
    return preg_replace("~$re~xie", '"$1$3"? "$0": (preg_match("/^on/i", "$2")? " ": "$0")', $tag);
}


Example usage

Online example :

$str = '
<button onclick="..javascript instruction..">
<button onclick="..javascript instruction.." value="..">
<button onclick=..javascript_instruction..>
<button onclick=..javascript_instruction.. value>
<hello word "" ontest = "hai"x="y"onfoo=bar/baz  />
';

echo $str . "\n----------------------\n";

echo remove_event_attributes($str);

Output:

<button onclick="..javascript instruction..">
<button onclick="..javascript instruction.." value="..">
<button onclick=..javascript_instruction..>
<button onclick=..javascript_instruction.. value>
<hello word "" ontest = "hai"x="y"onfoo=bar/baz  />

----------------------

<button >
<button  value="..">
<button >
<button  value>
<hello word "" x="y"   />

You might be better off using DOMDocument.

You can use it to iterate over the DOM tree represented by the HTML file you're trying to parse, looking for the various on* attributes that you want to remove.

This approach is more likely to succeed because DOMDocument actually understands the semantics of a HTML file, whereas regex is just a dumb string parser and inadequate for reliably parsing HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM