在PHP中将CSS白名单应用于HTML
假设我有以下在PHP中将CSS白名单应用于HTML,php,cakephp,Php,Cakephp,假设我有以下$string… <span style='text-decoration:underline; display:none;'>Some text</span> 类似于,但改用数组。因此,$string现在将是 <span style='text-decoration:underline;'>Some text</span> 一些文本 我用的是蛋糕,如果可以用消毒液来做,那就更好了。这很棘手,但你应该可以用DOMDocument来
$string…
<span style='text-decoration:underline; display:none;'>Some text</span>
类似于,但改用数组。因此,$string
现在将是
<span style='text-decoration:underline;'>Some text</span>
一些文本
我用的是蛋糕,如果可以用消毒液来做,那就更好了。这很棘手,但你应该可以用
DOMDocument
来做。这应该让你开始,但它可能需要一些严重的调整
// Load your html string
$dom = new DOMDocument();
$dom->loadHTML($your_html_string);
// Get all the <span> tags
$spans = $dom->getElementsByTagName("span");
// Loop over the span tags
foreach($spans as $span) {
// If they have a style attribute that contains "text-decoration:"
// attempt to replace the contents of the style attribute with only the text-decoration component.
if ($style = $span->getAttribute("style")) {
if (preg_match('/text-decoration:([^;]*);/i', $style)) {
$span->setAttribute("style", preg_replace('/^(.*)text-decoration:([^;]*);(.*)$/i', "text-decoration:$2;", $style);
}
// Otherwise, erase the style attribute
else $span->setAttribute("style", "");
}
}
$output = $dom->saveHTML;
我想你需要PHP的DOMDocument()对象来实现这一点。为什么这会偏离主题投票给Programmers.SE?我遗漏了什么?@Michael:我做了错误的近距离投票,有人跟踪了我。可能重复的@jchavannes可能重复的@jchavannes如果使用DOM路径,你似乎想要大量使用xpath和
/*[@style]
。当然,@jchavannes上面有一大块复杂的代码,如果你对这个项目的需求没有太多的想法,那么这应该足以让你朝着正确的方向前进。将其包装在function()
中,并根据注释中的建议(如果需要)使用xpath查询替换getElementsByTagName()
。
// This replaces the inner contents of the foreach ($spans as $span) above...
// Instead of the preg_replace()
$styles = explode(";", $style);
$replaced_style = FALSE;
foreach ($styles as $s) {
if (preg_match('/text-decoration/', $s) {
$span->setAttribute("style", $s);
$replaced_style = TRUE;
}
// If a text-decoration wasn't found, empty out the style
if (!$replaced_style) $span->setAttribute("style", "");
}