php js怎么去掉类属性,php – 从HTML标记中删除* JS事件属性

使用正则表达式进行标记时没有任何问题.但是使用正则表达式创建一个完整的HTML标记器是很多工作,很难做到正确.我建议使用正确的解析器,因为您可能还需要删除脚本标记等.

假设不需要完整的标记化器,可以使用以下正则表达式和代码从HTML标记中删除on *属性.

因为没有使用正确的标记化器,所以即使在脚本,注释,CDATA等中,它也会匹配看起来像标签的字符串.

无法保证所有输入/浏览器组合都会删除所有事件属性!请参阅下面的注释.

关于容错的注意事项:

浏览器通常容忍错误.

由于难以对标签进行标记并获取属性,因为当存在“无效”数据时,浏览器会看到它们.

由于浏览器之间的容错和处理不同,因此无法在所有情况下制定适用于所有浏览器的解决方案.

因此:某些浏览器(当前版本,过去版本或未来版本)可以处理我的代码认为不是标记的东西,作为标记,并执行JS代码.

在我的代码中,我试图模仿最近谷歌Chrome版本的标签(和容错/处理)的标记化.

Firefox似乎以类似的方式做到这一点.

IE 7有所不同,在某些情况下,它不是宽容的(这比它更宽容更好).

(IE 6 – 不要去那里.见XSS Filter Evasion Cheat Sheet)

相关链接:

代码

$redefs = '(?(DEFINE)

(? [a-z][^\s>/]*+ )

(? [^\s>/][^\s=>/]*+ ) # first char can be pretty much anything, including =

(? (?>

"[^"]*+" |

\'[^\']*+\' |

[^\s>]*+ # unquoted values can contain quotes, = and /

)

)

(? (?&attname)

(?: \s*+

= \s*+

(?&attval)

)?+

)

(? [^\s>] ) # most crap inside tag is ignored, will eat the last / in self closing tags

(?

(?: \s*+ # spaces between attributes not required: "style=color:red>bold red text

(?>

(?&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 = '( ^ ((?&attrib)) | ((?&crap)) )' . $redefs;

return preg_replace("~$re~xie", '"$1$3"? "$0": (preg_match("/^on/i", "$2")? " ": "$0")', $tag);

}

用法示例

$str = '

';

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

echo remove_event_attributes($str);

输出:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值