THINKPHP 清除HTML注释、换行符、空格、制表符等

thinkphp3.2 3.2中取消了配置文件中的 'TMPL_STRIP_SPACE' 属性,所以我们先来修改:\ThinkPHP\Library\Think\Template.class.php 文件

找到compiler方法:

/**
     * 编译模板文件内容
     * @access protected
     * @param mixed $tmplContent 模板内容
     * @return string
     */
    protected function compiler($tmplContent) {
        //模板解析
        $tmplContent =  $this->parse($tmplContent);
        // 还原被替换的Literal标签
        $tmplContent =  preg_replace_callback('/<!--###literal(\d+)###-->/is', array($this, 'restoreLiteral'), $tmplContent);
        // 添加安全代码
        $tmplContent =  '<?php if (!defined(\'THINK_PATH\')) exit();?>'.$tmplContent;

        /* 去除html空格与换行 */
        if(C('TMPL_STRIP_SPACE')) {
            //方法一
            // $find = array('~>\s+<~','~>(\s+\n|\r)~');
            // $replace = array('><','>');
            // $tmplContent = preg_replace($find, $replace, $tmplContent);
            //方法二
            // $tmplContent = trim($tmplContent); //清除字符串两边的空格
            // $tmplContent = preg_replace("/\t/","",$tmplContent); 
            // $tmplContent = preg_replace("/\r\n/","",$tmplContent); 
            // $tmplContent = preg_replace("/\r/","",$tmplContent); 
            // $tmplContent = preg_replace("/\n/","",$tmplContent); 
            // $tmplContent = preg_replace("/  /","",$tmplContent);  //匹配html中的空格 制表符
            //方法三
            $tmplContent = $this->compress_html($tmplContent);
        }

        // 优化生成的php代码
        $tmplContent = str_replace('?><?php','',$tmplContent);
        // 模版编译过滤标签
        Hook::listen('template_filter',$tmplContent);
        return strip_whitespace($tmplContent);
    }

如上所示,添加 if条件 使配置文件支持该属性。

if(C('TMPL_STRIP_SPACE'))

配置文件中就可以使用:

'TMPL_STRIP_SPACE' =>  true,       // 是否去除模板文件里面的html空格与换行

开启压缩了。

=====================================================================================

上面的代码展示了三种压缩方法,方法三使用了自定义的方法:

/** 
    * 压缩html : 清除换行符,清除制表符,去掉注释标记 
    * @param $string 
    * @return压缩后的$string
    * */ 
    public 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);
    }

另一种方法:

function higrid_compress_html($higrid_uncompress_html_source )
{
    $chunks = preg_split( '/(<pre.*?\/pre>)/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE );
    $higrid_uncompress_html_source = '';//[higrid.net]修改压缩html : 清除换行符,清除制表符,去掉注释标记
    foreach ( $chunks as $c )
    {
        if ( strpos( $c, '<pre' ) !== 0 )
        {
            //remove new lines & tabs
            $c = preg_replace( '/[\\n\\r\\t]+/', ' ', $c );
            //remove extra whitespace
            $c = preg_replace( '/\\s{2,}/', ' ', $c );
            //remove inter-tag whitespace
            $c = preg_replace( '/>\\s</', '><', $c );
            //remove CSS & JS comments
            $c = preg_replace( '/\\/\\*.*?\\*\\//i', '', $c );
        }
        $higrid_uncompress_html_source .= $c;
    }
    return $higrid_uncompress_html_source;
}

php压缩html函数代码总结

有些童鞋不 推荐压缩html , 主要原因除了上面所说的 php来压缩HTML注意事项 外,通过 gzip 压缩已经能达到很好的效果。另外,因为产生影响HTML的角色太多(静态,动态,前端动态),也没什么量化指标,所以很难控制压缩成什么样(代码写成什么程度)。代码更需要考虑执行效率,而不是传输效率。对于动态页面来说,HTML 的压缩有可能还会增加服务器的 CPU 负担,得不偿失。Google的压缩网页 是因为早期他希望首页文本尽可能控制在一个或两个包内,而且他的首页太重要了,流量也很离谱。压缩一个字节,总流量一算都是个不小的数字,自然也就是必要之举了。进一步的压缩存在问题,除非能像 Google 一样充分测试(Google 也仅压缩了少部分核心服务的页面),否则不推荐对 HTML 进行压缩处理。

=========================================

查看效果:

故事234:www.story234.com

荆州古城:www.jzeye.com

 

提示:如果页面使用了如下的代码

<volist name="jzgs" id="v" key="k"  offset="10" length='3' >
  <li {$k==1?"style='margin-left:0'":""} ><a href="/{$v.mode.url}/{$v.id}.html"  title="{$v.title}"><img src="{$v.img}" width=120 height=120 alt="{$v.title}"/><span>{$v.title}</span></a></li>
</volist>

三元运算符:

<li {$k==1?"style='margin-left:0'":""} >

方法一、方法二、压缩以后可能会产生错误 <listyle....
posted @ 2016-02-14 14:18  思如雨  阅读(4302)  评论(0编辑  收藏  举报