search
HomeBackend DevelopmentPHP Tutorialphp压缩HTML函数轻松实现压缩html/js/Css及注意事项_PHP

压缩HTML的起因
如何提高网页加载速度 ,需要怎么对html页面优化相信是每个拟提高建站技术站长曾想到的问题,其实网页优化的方法还是很多。

有童鞋询问higrid如何 压缩HTML,也就是说能不能 把所有的html、js、Css在运行前都压缩成一行,清除注释标记、换行符、空格、制表符等。这样一个直接的好处是 减小html页面体积来提高前端加载速度。很多人认为启动gzip,但一般启动gzip都比较少对html启动gzip压缩,因为现在的html都是动态的,不会使用浏览器缓存,而启用gzip的话每次请求都需要压缩,会比较消耗服务器资源,对js,css启动gzip比较好是因为js,css都会使用缓存。而大家也用了很多软件过滤一下压缩,也有 在线js/css/html压缩工具,higrid觉得也很麻烦,可读性很差。higrid认为如果将压缩功能做成一个函数的话,这样开发者看到的是未压缩的状态,但访客访问时,服务端的程序将 html页面进行压缩,清除注释标记、换行符、空格、制表符等 来达到 减小了html体积的目的。 如果您经常访问higrid.net, 右键查看一下 html源代码 ,会看到本篇 html源代码经过了压缩处理。包括higrid.net 提供的免费内容管理系统 ,输出的都是压缩html,去掉了空白、换行符、制表符。但higrid.net 上面也有一些例外,就是higrid.net 主要推荐 在线表格 、在线图形 ,包括 jquery这些演示 ,为了方便访客,就没有启动压缩。

因此,higrid个人觉得 压缩html 的最大好处就是一本万利,只要写好了一次函数,以后在需要运用的时候调用一下就可以了,所有程序都可以使用,不会增加任何额外的开发工作。今天higrid就给大家分享几个个人觉得好用的函数,请大家不妨试试看,相信大家会喜欢。

采用php来压缩HTML
由于higrid对 php 比较感兴趣,所以使用 php来压缩HTML,当然使用其他语言也差不多,例如使用 asp来压缩HTML,道理应该一样的。

higrid将 压缩html的功能用php写成一个函数 ,其实网上这样的 php压缩函数 也很多,不信你可以百度或者谷歌,但多数不是很好用,特别在 压缩js 或 压缩CSS 的时候,主要原因是一些 压缩注释 等方面不同导致出现问题。 先看这个函数:
复制代码 代码如下:
/**
* 压缩html : 清除换行符,清除制表符,去掉注释标记
* @param $string
* @return压缩后的$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);
}

php来压缩HTML注意事项
php来压缩HTM 实现的方式主要是用正则表达式去查找,替换。在html压缩的时候,主要要注意下面几点:

1.HTML 文档中,多个空白字符等价为一个空白字符。也就是说换行等空白字符的删除是不安全的,有可能导致部分元素的样式产生差异。
2.html中有一个pre, 表示 preformatted text. 里面的任何空白,都不能被删除,因此pre,textarea 标签里面的内容格式需要保留,不能压缩。
3.HTML 中有可能有 IE 条件注释。这些条件注释是文档逻辑的一部分,不能被删除。因此去掉html注释的时候,有些注释是不能去掉的,比如:
4.压缩嵌入式js中的注释要注意,因为可能注释符号会出现在字符串中,比如: var url = "http://www.higrid.net"; // 前面的//不是注释
5.对于动态页面来说,HTML 的压缩有可能还会增加服务器的 CPU 负担,得不偿失

higrid使用的php压缩html函数代码
由于注释对代码有作用,higrid使用的php压缩html函数代码 没有去掉注释,直接上代码。
复制代码 代码如下:
function higrid_compress_html($higrid_uncompress_html_source )
{
$chunks = preg_split( '/()/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE ); <br>$higrid_uncompress_html_source = '';//[higrid.net]修改压缩html : 清除换行符,清除制表符,去掉注释标记 <br>foreach ( $chunks as $c ) <br>{ <br>if ( strpos( $c, '<pre class="brush:php;toolbar:false">{ <br>//[higrid.net] remove new lines & tabs <br>$c = preg_replace( '/[\\n\\r\\t]+/', ' ', $c ); <br>// [higrid.net] remove extra whitespace <br>$c = preg_replace( '/\\s{2,}/', ' ', $c ); <br>// [higrid.net] remove inter-tag whitespace <br>$c = preg_replace( '/>\\s', '>// [higrid.net] remove CSS & JS comments <br>$c = preg_replace( '/\\/\\*.*?\\*\\//i', '', $c ); <br>} <br>$higrid_uncompress_html_source .= $c; <br>} <br>return $higrid_uncompress_html_source; <br>} <br> <br><strong>php压缩html函数代码总结<br></strong>有些童鞋不 推荐压缩html , 主要原因除了上面所说的 php来压缩HTML注意事项 外,通过 gzip 压缩已经能达到很好的效果。另外,因为产生影响HTML的角色太多(静态,动态,前端动态),也没什么量化指标,所以很难控制压缩成什么样(代码写成什么程度)。代码更需要考虑执行效率,而不是传输效率。对于动态页面来说,HTML 的压缩有可能还会增加服务器的 CPU 负担,得不偿失。Google的压缩网页 是因为早期他希望首页文本尽可能控制在一个或两个包内,而且他的首页太重要了,流量也很离谱。压缩一个字节,总流量一算都是个不小的数字,自然也就是必要之举了。进一步的压缩存在问题,除非能像 Google 一样充分测试(Google 也仅压缩了少部分核心服务的页面),否则不推荐对 HTML 进行压缩处理。 <br><br>但使用higrid.net 的 php压缩html函数 代码,能很好的解决这个问题。好了,还不快试试。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)