【问题标题】:Applying a CSS whitelist to HTML in PHP [closed]在 PHP 中将 CSS 白名单应用于 HTML [关闭]
【发布时间】:2011-07-22 08:02:18
【问题描述】:

假设我有以下$string...

<span style='text-decoration:underline; display:none;'>Some text</span>

我只想允许样式text-decoration,所以我想要一个像下面这样的PHP函数...

$string = stripStyles($string, array("text-decoration"));

类似于strip_tags,但使用数组代替。所以$string 现在将是...

<span style='text-decoration:underline;'>Some text</span>

我正在使用 Cake,所以如果这可以通过 Sanitize 完成,那就更好了。

【问题讨论】:

标签: php cakephp


【解决方案1】:

这很棘手,但您应该可以使用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;

最好尝试通过explode()ing on ; 解析样式属性

// 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", "");
}

【讨论】:

  • @jchavannes 你似乎想要很多
  • 如果使用 DOM 路由,请尝试使用带有 //*[@style] 的 xpath。
  • @jchavannes 上面是一个大而复杂的代码块,如果您不了解这个项目要求,应该足以让您朝着正确的方向前进。将其包装在 function() 中,并根据需要将 getElementsByTagName() 替换为 cmets 中建议的 xpath 查询。
猜你喜欢
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 2015-06-04
  • 1970-01-01
相关资源
最近更新 更多