墨文院 发文

PHP压缩html的函数代码

+关注 逍遥涛子

php编程实现html内容压缩的函数

要求:

在网页里面的js代码中不要使用//注释,/**/注释会自动剔除。

函数自动剔除标记直接的多余空白,而且会只能判断标记的属性的属性值是否被""包裹之间,如果有就剔除属性和属性值之间的所有空格,如果没有""就保留一个空格,避免破坏html结构。

<?php
//函数名: compress_html
//参数: $string
//返回值: 压缩后的$string
//逍遥涛子 928237152@qq.com
function compress_html($string) {
    $string = str_replace("\r\n", '', $string); //清除换行符
    $string = str_replace("\n", '', $string); //清除换行符
    $string = str_replace("\t", '', $string); //清除制表符
    $pattern = array (
                    "/> *([^ ]*) */",
                    "/\" /",
                    "/ \"/",
                    "'/\*[^*]*\*/'"
                    );
    $replace = array (
                    ">\\1<",
                    " ",
                    "",
                    "\"",
                    "\"",
                    ""
                    );
    return preg_replace($pattern, $replace, $string);
}


我要反馈

本文链接:http://www.71us.com/p/161283553562.html
下一篇:php压缩html代码的函数