I need to remove inline javascript for a given string. Examples:
If user typed: <img onload="something" />
I should need to convert into <img />
I created this PHP code and it works(apparently without issues):
http://writecodeonline.com/php/
function test_input($input){
//I have a list with all events but for this example I used two
$html_events = 'onload|onclick';
$pattern = "/(<[A-Z][A-Z0-9]*[^>]*)($html_events)([\s]*=[\s]*)('[^>]*'|\"[^>]*\")([^>]*>)/i";
$replacement = '$1$5';
while( preg_match($pattern, $input) ){
$input = preg_replace($pattern, $replacement, $input);
}
return htmlentities($input);
}
echo test_input('<img onload="alert(\'hello world\');" onclick="alert(\'hello world\');" />'). '<br />';
echo test_input('<img onload="alert(\'hello world\');"/>'). '<br />';
echo test_input('<div onload="alert(\'hello world\');" onclick="alert(\'hello world\');">hello buddies</div>'). '<br />';
I'm just looking for improvements or use cases that I did not supporting or that break my regex. I would appreciate if you tell me:
This: test_input('something bad');
breaks your regex.
Or if found an improvement that in a benchmark demonstrate better performance I should be happy to apply it as long as it does not break use cases already supported.
Thank You!
Update I finally used htmlpurifier
onload
oronlclick
attribute is found remove it \$\endgroup\$