preg_replace 删除样式 text/css 标签

preg_replace remove style text/css tag

我的 PHP 需要一些帮助,因为我很难摆脱 style type="text/css" 标签。我想删除样式标签以将其替换为空字符串。

当我尝试这个时:

if (strpos($inbox_message, '<style type="text/css">') !== false) {
    echo (preg_replace('/<style[^>]*>(([^<]|[<[^\/]|<\/[^s]|<\/s[^t])*)<\/style>/i','',$inbox_message));
}

它仍然会在 html 页面中显示样式标签。

显示的内容如下:

<style type="text/css"> body {position: relative; font-family: Segoe UI; font-size: 12px; } .pageHeader {color: #9C9C9C; font-size: 160%; padding: 0px 0px 6px 0px} .pageHeaderLogo {padding-right: 15px;} .pageHeaderTitle{border-left: 1px solid #CCCCCC; padding: 5px;} .pageFooter {width: 100%; background-color: #f2f2f2; font-size: 12px; font-family: Segoe UI; padding:4px 4px 4px 4px; } .pageFooterLogo {text-align:right; width:100%} .padCells { padding: 0px 6px 0px 0px; } .preHeader {display: none !important; visibility:hidden; opacity:0; color:transparent; height:0; width:0; }</style>

能否举例说明如何使用 preg_replace 找到 style type=text/css 标签以便删除它们?

谢谢。

编辑:抱歉,我意识到我只需要删除样式标签中的正文,因为我想保留样式中的其他标签。

/*GENERAL*/
    table{width:100%}
    body{background-color:#ebebeb; width: 100%; margin:0; padding:0; -webkit-font-smoothing: antialiased;font-family: "Segoe UI",SegoeUI,"Helvetica Neue",Helvetica,sans serif; -webkit-text-size-adjust: 100%;}
    div.ms-article-container #emailbodyouter .emailbodyinner section{margin:0}
    div.ms-article-container #emailbodyouter .emailbodyinner table div {margin:0}
    div.content-article #emailbodyouter .emailbodyinner section{margin:0}
    div.content-article #emailbodyouter .emailbodyinner table div {margin:0}

字面答案:

$inbox_message = preg_replace('#<style type="text/css">.*?</style>#s', '', $inbox_message);

您不需要检查它是否存在 — 如果不存在,preg_replace 将不会执行任何操作。你不需要担心标签里面有什么——非贪婪量词会处理它(只要你没有任何机会有一个嵌套的 <style> 标签,这会很特别) .如果您选择其他分隔符,则无需担心转义斜杠。

非文字答案:Beware Zalgo

$doc = new DOMDocument();
$doc->loadHTML($inbox_message);
$xpath = new DOMXpath($doc);
$styles = $xpath->query('//style[@type="text/css"]');
if ($styles) {
  foreach ($styles as $style) {
    $style->parentNode->removeChild($style);
  }
}
$inbox_message = $doc->saveHTML();

编辑 问题改变后:由于默认情况下没有 CSS 解析器,我们最终不得不使用正则表达式。这样的事情应该没问题。 Zalgo 方法:

$inbox_message = preg_replace_callback('#<style type="text/css">.*?</style>#s', function($match) {
  return preg_replace('#body\s*{(?:[^"}]|"[^"]*")*}#', '', $match[0]);
}, $inbox_message);

反Zalgo方法:

$doc = new DOMDocument();
$doc->loadHTML($inbox_message);
$xpath = new DOMXpath($doc);
$styles = $xpath->query('//style[@type="text/css"]');
if ($styles) {
  foreach ($styles as $style) {
    $style->textContent = preg_replace('#body\s*{(?:[^"}]|"[^"]*")*}#', '', $style->textContent);
  }
}
$inbox_message = $doc->saveHTML();