php压缩html源码2.0
注意事项
只支持压缩含一个<script></script>的html,且变量内多个空格也会被压缩为一个
压缩内容
- html
去除<!-- -->内的全部内容
多个空白符变为一个空格去除> <内的空白符
- css
去除/* */内的全部内容
多个空白符变为一个空格
去除【'】【"】【{】【}】【:】【;】【,】【<style>】【</style>】两端的空白符
- js
去除/* */内的全部内容去除//行内容多个空白符变为一个空格去除【(】【)】【{】【}】【=】【||】【&&】【+】【'】【"】【:】【;】【,】【<script>】【</script>】两端的空白符
代码
<?php
function miniHtml($s)
{
//注:只支持压缩含一个<script></script>的html,且变量内多个空格也会被压缩为一个
//提取css跟javascript单独处理
preg_match('/\<style\>[\s\S]*\<\/style\>/',$s,$style);
preg_match('/\<script\>[\s\S]*\<\/script\>/',$s,$script);
empty($style)?$style='':$style = $style[0];
empty($script)?$script='':$script = $script[0];
//处理html
$html = preg_replace('/\<\!\-\-[\s\S]*\-\-\>/','',$s);
$html = preg_replace('/[\s]+/',' ',$html);
$html = preg_replace('/>[\s]+</','><',$html);
//处理css
$style = preg_replace('/\/\*[\s\S]*\*\//','',$style);
$style = preg_replace('/[\s]+/',' ',$style);
$style = preg_replace('/[\s]?\'[\s]?/','\'',$style);
$style = preg_replace('/[\s]?"[\s]?/','"',$style);
$style = preg_replace('/[\s]?\{[\s]?/','{',$style);
$style = preg_replace('/[\s]?\}[\s]?/','}',$style);
$style = preg_replace('/[\s]?\:[\s]?/',':',$style);
$style = preg_replace('/[\s]?;[\s]?/',';',$style);
$style = preg_replace('/[\s]?,[\s]?/',',',$style);
$style = preg_replace('/[\s]?\<style\>[\s]?/','<style>',$style);
$style = preg_replace('/[\s]?\<\/style\>[\s]?/','</style>',$style);
//处理js
$script = preg_replace('/\/\*[\s\S]*\*\//','',$script);
$script = preg_replace('/^[\s]*\/\/.*$/m','',$script);
$script = preg_replace('/[\s]+/',' ',$script);
$script = preg_replace('/[\s]?\([\s]?/','(',$script);
$script = preg_replace('/[\s]?\)[\s]?/',')',$script);
$script = preg_replace('/[\s]?\{[\s]?/','{',$script);
$script = preg_replace('/[\s]?\}[\s]?/','}',$script);
$script = preg_replace('/[\s]?\=[\s]?/','=',$script);
$script = preg_replace('/[\s]?\|\|[\s]?/','||',$script);
$script = preg_replace('/[\s]?\&\&[\s]?/','&&',$script);
$script = preg_replace('/[\s]?\+[\s]?/','+',$script);
$script = preg_replace('/[\s]?\'[\s]?/','\'',$script);
$script = preg_replace('/[\s]?"[\s]?/','"',$script);
$script = preg_replace('/[\s]?\:[\s]?/',':',$script);
$script = preg_replace('/[\s]?;[\s]?/',';',$script);
$script = preg_replace('/[\s]?,[\s]?/',',',$script);
$script = preg_replace('/[\s]?\<script\>[\s]?/','<script>',$script);
$script = preg_replace('/[\s]?\<\/script\>[\s]?/','</script>',$script);
//合并css跟js
$html = preg_replace('/\<style\>[\s\S]*\<\/style\>/',$style,$html);
$html = preg_replace('/\<script\>[\s\S]*\<\/script\>/',$script,$html);
return $html;
}
上一篇: PHP - Lara
下一篇: CSS设置内外边距