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
Example usage
Online example:
Output: