用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2172|回复: 0
收起左侧

[核心代码 Core] [翻译]压缩HTML输出为一行

[复制链接]
发表于 2017-2-20 13:09:17 | 显示全部楼层 |阅读模式
(不知道有没有人发过,原文地址https://github.com/bcit-ci/CodeIgniter/wiki/Compress-HTML-output/)
移除HTML代码中无用的空格(除js代码)
第一步:启用钩子 config/config.php
PHP复制代码
$config['enable_hooks'] = TRUE;
复制代码

第二步:加入压缩的钩子 config/hooks.php
PHP复制代码
// Compress output
$hook['display_override'][] = array(
    'class' => '',
    'function' => 'compress',
    'filename' => 'compress.php',
    'filepath' => 'hooks'
);
复制代码

第三步:定义一个“display_override”钩子
PHP复制代码
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function compress()
{
    ini_set("pcre.recursion_limit", "16777");
    $CI =& get_instance();
    $buffer = $CI->output->get_output();
 
    $re = '%# Collapse whitespace everywhere but in blacklisted elements.
        (?>             # Match all whitespans other than single space.
          [^\S ]\s*     # Either one [\t\r\n\f\v] and zero or more ws,
        | \s{2,}        # or two or more consecutive-any-whitespace.
        ) # Note: The remaining regex consumes no text at all...
        (?=             # Ensure we are not in a blacklist tag.
          [^<]*+        # Either zero or more non-"<" {normal*}
          (?:           # Begin {(special normal*)*} construct
            <           # or a < starting a non-blacklist tag.
            (?!/?(?:textarea|pre|script)\b)
            [^<]*+      # more non-"<" {normal*}
          )*+           # Finish "unrolling-the-loop"
          (?:           # Begin alternation group.
            <           # Either a blacklist start tag.
            (?>textarea|pre|script)\b
          | \z          # or end of file.
          )             # End alternation group.
        )  # If we made it here, we are not in a blacklist tag.
        %Six'
;
 
    $new_buffer = preg_replace($re, " ", $buffer);
 
    // We are going to check if processing has working
    if ($new_buffer === null)
    {
        $new_buffer = $buffer;
    }
 
    $CI->output->set_output($new_buffer);
    $CI->output->_display();
}
 
/* End of file compress.php */
/* Location: ./system/application/hooks/compress.php */
复制代码

上面的代码保存在application/hooks/compress.php

评分

参与人数 1威望 +5 收起 理由
Hex + 5 赞一个!

查看全部评分

本版积分规则