2017-05-03 48 views
-2

我有这样的网站,例如,我试图将所有样式标记放在头标记内的身体标记中。PHP:将所有CSS代码从身体移动到头标记

<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

正则表达式不是正确的工具。随着代码复杂性的增加,正确度越来越高。相反,你应该使用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>"; 
+0

我得到这样的标签导航误差在实体无效,标签页脚无效 – Vishnu

+0

你应该张贴导致你错误的代码。提供的代码适用于您提供的示例... http://phpfiddle.org/main/code/pi8h-2wi2 –

+0

我已编辑我的问题中的代码,请检查 – Vishnu