Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 . "
----------------------
";

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"   />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...