PHP压缩html的函数

唯一要求就是在网页里面的js代码中不要使用//注释,/**/注释会自动剔除。
函数自动剔除标记直接的多余空白,而且会只能判断标记的属性的属性值是否被""包裹之间,如果有就剔除属性和属性值之间的所有空格,如果没有""就保留一个空格,避免破坏html结构。
比如
<a href=http://www.baidu.com     style="font-size : 14px;  "> baidu </a>
压缩后:
<a href=http://www.baidu.com style="font-size:14px;">baidu</a>
又如:
<a href="http://www.baidu.com"     style="font-size : 14px;  "> baidu </a>
压缩后:
<a href="http://www.baidu.com"style="font-size:14px;">baidu</a>
//函数名: compress_html
//参数: $string
//返回值: 压缩后的$string
function compress_html($string) {
    $string = str_replace("\r\n", '', $string); //清除换行符
    $string = str_replace("\n", '', $string); //清除换行符
    $string = str_replace("\t", '', $string); //清除制表符
    $pattern = array (
                    "/> *([^ ]*) *</", //去掉注释标记
                    "/[\s]+/",
                    "/<!--[^!]*-->/",
                    "/\" /",
                    "/ \"/",
                    "'/\*[^*]*\*/'"
                    );
    $replace = array (
                    ">\\1<",
                    " ",
                    "",
                    "\"",
                    "\"",
                    ""
                    );
    return preg_replace($pattern, $replace, $string);
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值