我最终会回答你的问题,让我得到你即将当你还没有说做主持,虽然
这样的解释,我不明白为什么你会想要做到这一点。从用户收集原始html并在其他地方显示它被认为是一个巨大的安全漏洞。使用纯粹的正则表达式来摆脱所有的javascript将会很困难。清除脚本标记很容易,但删除内联JavaScript将是困难的部分。虽然有可能,我会建议寻找另一种方式来进行比给用户的网页的JavaScript的剥离版本之外的其他任务。你可以做到这一点
一种方式是通过iframe。使用
<iframe src="html_you_want_to_strip" sandbox=""></iframe>
将禁用在iframe中运行的所有javascript。请记住,还有其他方式可以在不使用JavaScript的情况下将恶意项目加载到您的网站中。
现在,我已经解释了,当谈到剥JavaScript,以便回答你的问题,你应该做的,
A.删除只从身体脚本标记,只是头:
最好删除javascript时获得粒度的方法是使用PHP的DOMDocument类。基本上,你会了将文档装入此DOMDocument类剥夺你想要的任何脚本标记它。例如,如果你只是想摆脱在体内的脚本标签,你可以写这样的事情:
<?php
$html = "the HTML you want filtered";
$DOM = new DOMDocument('1.0','utf-8');
$DOM->loadHTML($html);
$bodyTags = $DOM->getElementsByTagName('body');
/*
We will run under the assumption that the user has the ability to add two
body tags and hide information in the second one, that is why we don't
just use $DOM->getElementsByTagName('body')[0]
*/
foreach($bodyTags as $body){
foreach($body->getElementsByTagName('script') as $script){
$script->parentNode->removeChild($script);
/*
The reason we have to this is because you cant just do
$script->remove(), that would be too easy :)
*/
}
}
相同的代码上面可以用来剥去头标记的脚本。如果您想删除具有特定索引的项目,则可以使用您的foreach执行以下操作:
$i=0;
foreach($body->getElementsByTagName('script') as $script){
if($i!==(INDEX_TO_KEEP)){
$script->parentNode->removeChild($script);
}
}
B.删除内联javascript
我们可以使用相同的DOMDocument解析器,除了解析所有元素,这次查找所有JavaScript事件(谢天谢地所有的开始)。代码如下所示。
<?php
//starting where the last code leaves off
foreach($DOM->getElementsByTagName('*') as $element){
//This selects all elements
foreach($element->attributes as $attribute){
if(preg_match('/on.*/',$attribute)==1){
/*
"on" looks for on and ".*" states that there
can be anything after the on (onmousemove,onload,etc.)
*/
$element->removeAttribute($attribute)
}
}
}
在你的代码的最后,您将要保存的剥离HTML,然后返回给用户
$parsedHTML = $DOM->saveHTML()
“答案我喜欢关于这一主题的最多的是从平” - 殇它不起作用。 https://pastebin.com/t28dn6Zt – Quentin