【发布时间】:2019-03-12 03:22:04
【问题描述】:
我正在尝试允许使用数组的一些标签和属性,并删除其余的
这是我的例子:
$allowed=array("img", "p", "style");
$text='<img src="image.gif" onerror="myFunction()" style="background:red" onclick="myFunction()">
<p>A function is triggered if an error occurs when loading the image. The function shows an alert box with a text.
In this example we refer to an image that does not exist, therefore the onerror event occurs.</p>
<script>
function myFunction() {
alert(\'The image could not be loaded.\');
}
</script>';
使用$text= preg_replace('#<script(.*?)>(.*?)</script>#is', '', $text);
我可以删除带有内容的脚本标签,但我需要删除不在 $allowed 数组中的所有内容
【问题讨论】:
-
你可以使用我写的这个 HTML 压缩器,通过一些工作就可以删除特定的标签。它具有不缩小特定标签的能力。因此,您可以将其更改为删除它们(可能)github.com/ArtisticPhoenix/MISC/blob/master/Lexers/… 它以 Lexer/Parser 类型的方式使用正则表达式。
-
@ArtisticPhoenix
ini_set('display_errors', 1);不应在生产环境中使用,可能需要在该 GIT 中添加评论。 -
这并不是真正的生产代码,它实际上是这里的另一个答案。这就是为什么它在 MISC 中。它确实说
//For debugging -
有嵌套标签吗?例如
<div><p>text</p><img />more text<p>text</p></div> -
是的,内容来自文本编辑器
标签: php preg-replace