这是一笔交易,我正在做一个帮助人们教HTML的项目。当然,我很害怕Scumbag Steve(见图1)。如何从字符串中去除特定标签和特定属性?
,所以我想阻止ALL HTML标签,除了那些批准了一个非常具体的白名单。
在这些已批准的HTML标记中,我希望删除有害的属性。如onload
和onmouseover
。另外,根据白名单。
我想过正则表达式,但我敢肯定它是邪恶的,对工作没什么帮助。
任何人都可以给我一个正确的方向推动吗?
在此先感谢。
图1
这是一笔交易,我正在做一个帮助人们教HTML的项目。当然,我很害怕Scumbag Steve(见图1)。如何从字符串中去除特定标签和特定属性?
,所以我想阻止ALL HTML标签,除了那些批准了一个非常具体的白名单。
在这些已批准的HTML标记中,我希望删除有害的属性。如onload
和onmouseover
。另外,根据白名单。
我想过正则表达式,但我敢肯定它是邪恶的,对工作没什么帮助。
任何人都可以给我一个正确的方向推动吗?
在此先感谢。
图1
require_once 'library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
// this one is needed cause otherwise stuff
// considered harmful like input's will automatically be deleted
$config->set('HTML.Trusted', true);
// this line say that only input, p, div will be accepted
$config->set('HTML.AllowedElements', 'input,p,div');
// set attributes for each tag
$config->set('HTML.AllowedAttributes', 'input.type,input.name,p.id,div.style');
// more extensive way of manage attribute and elements... see the docs
// http://htmlpurifier.org/live/configdoc/plain.html
$def = $config->getHTMLDefinition(true);
$def->addAttribute('input', 'type', 'Enum#text');
$def->addAttribute('input', 'name', 'Text');
// call...
$purifier = new HTMLPurifier($config);
// display...
$html = $purifier->purify($raw_html);
- 注:,你问这个代码将运行作为白名单,只输入,p和DIV被接受,只有某些码属性被接受。
我认为你可以在IE中使用样式属性做一些伤害。至少在正常的样式表中,您可以引用基于JavaScript的行为文件。 – ThiefMaster 2012-03-28 21:18:04
@ThiefMaster:是的,但不要慌张HTMLPurifier会自动删除任何对.htc文件的引用! ;-) – 2012-03-28 21:29:39
完美答案!记录和一切! + 1 +接受。谢谢! – 2012-03-29 12:37:05
使用Zend framework 2 strip tags。下面的示例接受ul,li,p ...和img(仅用于src属性)和链接(仅用于href atttribute)。其他一切都将被剥夺。如果我没有错zf1做同样的事情
$filter = new \Zend\Filter\StripTags(array(
'allowTags' => array(
'ul'=>array(),
'li'=>array(),
'p'=>array(),
'br'=>array(),
'img'=>array('src'),
'a'=>array('href')
),
'allowAttribs' => array(),
'allowComments' => false)
);
$value = $filter->filter($value);
其实使用正则表达式是要走的路。至少,我会强烈推荐它。他们会为您解析的字符串提供极大的灵活性和控制器。 – Deleteman 2012-03-27 20:32:29
要走的路http://htmlpurifier.org/ – 2012-03-27 20:32:31
@Deleteman:是的,但我已经说过我想要一个**白名单**,而不是**黑名单**,意思是一切都被封锁了,除了一些特定的标签。我不知道如何用RegEx处理这个问题(如果你可以抛出一个小规模的例子,这将是非常棒的) – 2012-03-27 20:34:15