我正在尝试使用HTMLPurifier通过向段落添加类属性来转换HTML。
例如,对于此输入HTML:
<p>This is a paragraph</p>
<p>Another one</p>
这将是输出:
<p class="myclass">This is a paragraph</p>
<p class="myclass">Another one</p>
我在该网站上阅读了该文档和一些论坛帖子,但我无法弄清楚我应该怎么做呢?
提前致谢。
答案 0 :(得分:3)
以下是一个快速而肮脏的示例,您可以自行测试:
<?php
require_once 'lib/library/HTMLPurifier.auto.php';
class HTMLPurifier_AttrTransform_AnchorClass extends HTMLPurifier_AttrTransform
{
public function transform($attr, $config, $context)
{
// keep predefined class
if (isset($attr['class']))
{
$attr['class'] .= ' myclass';
}
else
{
$attr['class'] = 'myclass';
}
return $attr;
}
}
$dirty_html = '<a href=""></a>
<a target="_blank" href=""></a>
<a href="" class="toto"></a>
<a href="" style="oops"></a>';
$config = HTMLPurifier_Config::createDefault();
$htmlDef = $config->getHTMLDefinition(true);
$anchor = $htmlDef->addBlankElement('a');
$anchor->attr_transform_post[] = new HTMLPurifier_AttrTransform_AnchorClass();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);
var_dump($clean_html);
It outputs:
string '<a href="" class="myclass"></a>
<a href="" class="myclass"></a>
<a href="" class="toto myclass"></a>
<a href="" class="myclass"></a>' (length=135)