Sanitize 有一个 remove_contents 选项,您可以使用它。
来自测试代码:
Sanitize.fragment('foo bar <div>baz<span>quux</span></div>',
:remove_contents => true
)
#=> 'foo bar '
请参阅test example。
对于上述情况,您可以在 remove_contents 的值中指定要删除的标签,如下所示:
Sanitize.fragment("<script>alert('test js');</script><p>Hello world</p>",
remove_contents: ["script"]
)
#=> " Hello world "
或者,您可以指定要保留的元素并删除其他所有元素,如下所示:
html = "<strong>foo</strong><div>bar</div>"
Sanitize.fragment(html,
elements: ['h1','h2','h3','h4','h5','h6','p','ul','ol','li','small','b','strong','em','i','u'],
remove_contents: true
)
#=> "<strong>foo</strong> "
如果例如您只想删除 <script> 之类的标签并保持其他所有内容不变,您可以执行以下操作:
html = "<strong>foo</strong><script>bar</script><p>baz</p><div>foobar</div>"
Sanitize.fragment(html,
Sanitize::Config.merge(Sanitize::Config::BASIC, remove_contents: ['script'])
)
#=> "<strong>foo</strong><p>baz</p> foobar "
请注意,最后一个<div> 的内容仍然存在,因为它没有包含在remove_contents 数组中,但它的<div> 标记已被删除(Sanitize::Config::BASIC 的工作原理就是这样)。将Sanitize::Config::BASIC 替换为Sanitize::Config::RELAXED 以获得较少限制的过滤规则,这将在此示例中保留<div> 标记。
虽然我找到的唯一文档是 in the code itself,但还有许多其他可能。