使用 PHP 从 html 输入中删除某些标签

Remove certain tags from html input with PHP

我有一个表单,用户可以使用 html 设置他们自己的输入样式。我想用 PHP 清除服务器端的输入。但是,我想确保所有输入都是安全的并且符合我的要求。我已经有了 XSS 保护,所以这 与删除脚本无关。

当用户提供输入时,我想删除 pimgahrbr、[= 以外的标签17=]、trtdpreulollispan(基本上所有文本格式div 除外)。我想删除 <a>href<img>src<p>style 以外的任何属性。对于 <p> 样式,我只想保留以下属性:

此外,我希望能够将文本裁剪到一定长度,同时保留结束标签并确保每个开始标签也有一个结束标签。

例如,Stack Overflow 编辑器如何在保存输入并显示给用户之前解析和清理输入?

谢谢。

我使用 http://htmlpurifier.org/ 清理 html-输入。您可以定义允许的标签、属性和样式。我添加了我项目中的代码作为示例。

    $configuration = HTMLPurifier_Config::createDefault();
    $configuration->set('Attr.EnableID', true);
    $configuration->set('AutoFormat.RemoveEmpty', true);
    $configuration->set('AutoFormat.RemoveEmpty.RemoveNbsp', true);
    $configuration->set('HTML.AllowedAttributes', array('span.style', '*.id', '*.src', 'a.href', 'table.style', 'img.style', 'td.colspan', 'td.rowspan', 'td.style'));
    $styles = array('margin-left', 'color', 'background-color', 'text-decoration', 'font-weight', 'font-style', 'border', 'border-collapse', 'height');
    $configuration->set('CSS.AllowedProperties', $styles);
    $htmlPurifier = new HTMLPurifier($configuration);
    return $htmlPurifier->purify($html);