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

使用PHP从html输入中删除某些标记,php,html,parsing,dom,sanitization,Php,Html,Parsing,Dom,Sanitization,我有一个表单,用户可以在其中使用html为自己的输入设置样式。我想用PHP清理服务器端的输入。但是,我希望确保所有输入都是安全的,并且与我希望的匹配。我已经有XSS保护,所以这不是关于删除脚本。 当用户提供输入时,我想删除除p,img,a,hr,br,tbody,tr,td,pre,ul,ol,li,和span(基本上所有文本格式都不是divs)。我想删除除的href、的src和的样式以外的任何属性。对于样式,我只想保留以下属性: color 背景色 行高 任何以text- 此外,我希望能够

我有一个表单,用户可以在其中使用html为自己的输入设置样式。我想用PHP清理服务器端的输入。但是,我希望确保所有输入都是安全的,并且与我希望的匹配。我已经有XSS保护,所以这不是关于删除脚本。

当用户提供输入时,我想删除除
p
img
a
hr
br
tbody
tr
td
pre
ul
ol
li
span
(基本上所有文本格式都不是divs)。我想删除除
href
src
样式
以外的任何属性。对于
样式,我只想保留以下属性:

  • color
  • 背景色
  • 行高
  • 任何以
    text-
此外,我希望能够将文本裁剪到一定长度,同时保留结束标记,并确保每个开始标记也有结束标记

例如,在保存输入并将其显示给用户之前,堆栈溢出编辑器如何解析和清理输入

谢谢。

我用来清理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);
我用它来清理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);

我不知道SO编辑器背后的代码。如果你向我们展示你的代码,也许我们可以帮助你改进它。我的代码来自Summernote编辑器。澄清一下,这是关于后端的。你使用CKEditor吗?我不知道SO编辑器背后的代码。如果你向我们展示你的代码,也许我们可以帮助你改进它。我的代码来自Summernote编辑器。澄清一下,这是关于后端的。你使用CKEditor吗?太棒了。实际上,我一直在使用它来净化带有自动配置的脚本,但我不知道它可以完成所有这些。谢谢,太棒了。实际上,我一直在使用它来净化带有自动配置的脚本,但我不知道它可以完成所有这些。谢谢