voilab / htmlcleaner
基于SimpleXML的HTML清理器,速度快且可定制
Requires
- php: >=5.6.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-20 20:56:54 UTC
README
基于SimpleXML的HTML清理器,速度快且可定制
安装
通过Composer
在项目根目录下创建一个composer.json文件
{ "require": { "voilab/htmlcleaner": "0.*" } }
$ composer require voilab/htmlcleaner
样本数据集
<p> Some paragraph with <strong>bold</strong> or <em><u><i>nested tags</i></u></em>. </p> <p> And a second paragraph (so two roots elements, here) with <a href="somesite.org">a cool link</a>, <a href="javascript:alert('BAM!');">a bad link</a> and some <span class="red">nice attributes to try to keep</span>. </p>
基本用法
移除所有标签
use \voilab\cleaner\HtmlCleaner; $cleaner = new HtmlCleaner(); $raw_html = '...'; // take sample dataset above echo $cleaner->clean($raw_html);
允许某些标签
// create cleaner... $cleaner->addAllowedTags(['p', 'strong']); // call clean method
允许某些标签和属性(无论标签)
// create cleaner... $cleaner ->addAllowedTags(['p', 'span']) ->addAllowedAttributes(['class']); // call clean method
仅在特定标签上允许某些属性
// create cleaner... $cleaner ->addAllowedTags(['p', 'span']) ->addAllowedAttributes([ // keep attribute "class" only for spans new \voilab\cleaner\attribute\Keep('class', 'span'), // you can use this shorthand too, as a string 'style:span' ]); // call clean method
高级用法
处理器
处理器用于在将其插入新的SimpleXMLElement(处理的基础)之前准备HTML字符串。它们也用于清理后的HTML格式化。这是一种预处理和后处理。
预处理必须移除不允许的标签。
标准处理器
标准处理器使用strip_tags()
来移除不允许的标签。处理后,处理器会从字符串中移除所有换行符。
自定义处理器
您可以通过实现\voilab\cleaner\processor\Processor
来创建自己的处理器。不要忘记,预处理负责移除所有不允许的标签。
属性
属性类用于验证属性及其内容。默认情况下,允许的属性变为\voilab\cleaner\attribute\Keep
。每个“不允许”的属性变为\voilab\cleaner\attribute\Remove
。
这两个属性类型不需要您实例化。所有在setAllowedTags()
中提供的字符串属性都将转换为Keep
类。
Js属性
您可能想保留一些属性但检查其内容。这适用于href
属性。它可以包含有效的URL或一些javascript注入。为此已经创建了一个属性验证器
$cleaner ->addAllowedTags(['a']) ->addAllowedAttributes([ new \voilab\cleaner\attribute\Js('href') ]);
请注意,允许的属性可以或不绑定到特定标签。在上面的示例中,href属性将对每个HTML标签有效。如果要将属性绑定到标签,您需要将其指定为第二个参数。
已知限制
根混合内容
根位置外不允许有标签外的混合内容。
<!-- not valid: parts "some root " and " special " will disappear --> some root <strong>mixed</strong> special <em>content</em> <!-- valid --> <p>some root <strong>mixed</strong> special <em>content</em></p> <!-- also valid --> <p>some root element</p> <p>and an other root element</p>
使用标准处理器时的不良HTML格式
如果HTML格式不正确,清理器将抛出\Exception
。字符串需要完全正确,因为它由simplexml_load_string($html)
处理,它非常严格
- 标签必须关闭(
<p></p>
或<br />
) - 属性必须用双引号括起来(
<hr class="test" />
) - 在属性内容中不允许使用双引号,必须在调用
HtmlCleaner::clean()
之前将其转换为"
- 在内容中不允许使用
<
和&
,必须在调用HtmlCleaner::clean()
之前分别转换为<
和&
这些限制将在未来的版本中解决。
测试
$ vendor/bin/phpunit --bootstrap vendor/autoload.php tests/
安全性
如果您发现任何安全相关的问题,请使用问题跟踪器。
鸣谢
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。