PHP:将所有CSS代码从body标记移动到head标记

时间:2017-05-03 16:33:43

标签: php regex

我有这样的网站,例如,我试图将所有这些样式标签放在head标签内的body标签中。

    <html>
    <head>

    </head>
    <body>
<nav>navbar</nav>
    <div>bla ba ... lots of html contents</div>

    <style>
    .h1
    {
    color:red;
    }
    </style>
    <div>bla ba ... lots of html contents</div>
    <style>
    .h2
    {
    green;
    }
    </style>

<footer>
footer
</footer>
    </body>
    </html>

我想在php中做,我尝试了以下代码。但是它会减慢我的页面吗?还有其他替代方案吗?

$output = ob_get_contents();
ob_end_clean();

$output = preg_replace('/\s+/', ' ', $output);

preg_match_all('/<style>(.*?)<\/style>/s', $output, $mat);
$output = preg_replace('/<style>(.*?)<\/style>/s', '', $output);

foreach($mat[0] as $headsty)
{
$output = str_replace("</head>",$headsty."</head>",$output);
}

echo $output;

1 个答案:

答案 0 :(得分:1)

正则表达式不是正确的工具。随着代码复杂性的增加,变得更加困难。相反,你应该使用PHP :: Dom类。您可以使用它来扫描HTML并提取<style>元素,然后将其重写为<head>元素,如此...

$html = <<<EOF
    <html>
    <head>

    </head>
    <body>
    <nav>navbar</nav>
    <div>bla ba ... lots of html contents</div>

    <style>
    .h1
    {
    color:red;
    }
    </style>
    <div>bla ba ... lots of html contents</div>
    <style>
    .h2
    {
    green;
    }
    </style>

    <footer>
        footer
    </footer>
    </body>
    </html>
EOF;

// Suppress warnings about invalid elements
libxml_use_internal_errors(true);

$dom = new DOMDocument;
$dom->loadHTML($html);

$styles = $dom->getElementsByTagName('style');

$head = $dom->getElementsByTagName('head')->item(0);
foreach ($styles as $style) {
    $head->appendChild($style);
}

echo "<pre>" . htmlentities( $dom->saveHTML() ) . "</pre>";