true, 'remove_whitespace' => true, 'compress_css' => true, 'compress_js' => true, 'preserve_line_breaks' => false, 'preserve_pre_content' => true, 'preserve_textarea_content' => true, 'preserve_script_content' => true, 'preserve_style_content' => true ); /** * 需要保护的标签内容 */ private $preserve_tags = array('pre', 'textarea', 'script', 'style'); /** * 保护的内容存储 */ private $preserved_content = array(); /** * 构造函数 */ public function __construct($options = array()) { $this->options = array_merge($this->options, $options); } /** * 主要压缩方法 * * @param string $html HTML内容 * @return string 压缩后的HTML */ public function compress($html) { if (empty($html)) { return $html; } // 重置保护内容 $this->preserved_content = array(); // 1. 保护需要保留原始格式的内容 $html = $this->preserveContent($html); // 2. 移除HTML注释 if ($this->options['remove_comments']) { $html = $this->removeComments($html); } // 3. 压缩空白字符 if ($this->options['remove_whitespace']) { $html = $this->compressWhitespace($html); } // 4. 恢复保护的内容 $html = $this->restoreContent($html); // 5. 压缩内联CSS和JS if ($this->options['compress_css'] || $this->options['compress_js']) { $html = $this->compressInlineCode($html); } return trim($html); } /** * 保护需要保留原始格式的内容 * * @param string $html * @return string */ private function preserveContent($html) { $index = 0; // 保护
 标签内容
        if ($this->options['preserve_pre_content']) {
            $html = preg_replace_callback(
                '/]*>.*?<\/pre>/is',
                function($matches) use (&$index) {
                    $placeholder = "";
                    $this->preserved_content[$placeholder] = $matches[0];
                    $index++;
                    return $placeholder;
                },
                $html
            );
        }
        
        // 保护