如何从字符串中删除特定标记和特定属性?

Mad*_*iha 3 html php whitelist

这是交易,我正在制作一个项目来帮助人们教HTML.当然,我害怕那个Scumbag Steve(见图1).

所以我想阻止所有 HTML标记,除了那些在非常特定的白名单上批准的标记.

在这些已批准的HTML标记中,我也希望删除有害属性.如onloadonmouseover.另外,根据白名单.

我想到了正则表达式,但我很确定它是邪恶的,对这项工作没有多大帮助.

谁能给我一个正确方向的推动?

提前致谢.


图.1.

Scumbag Steve

Luc*_*ofi 5

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);
Run Code Online (Sandbox Code Playgroud)
  • 注意:正如您所知,此代码将作为白名单运行,只接受输入,p和div,并且只接受某些属性.