0

0

压缩多个CSS与JS文件的php代码

php中文网

php中文网

发布时间:2016-07-25 09:04:42

|

1135人浏览过

|

来源于php中文网

原创

  1. header('Content-type: text/css');
  2. ob_start("compress");
  3. function compress($buffer) {
  4. /* remove comments */
  5. $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
  6. /* remove tabs, spaces, newlines, etc. */
  7. $buffer = str_replace(array(" ", " ", " ", " ", ' ', ' ', ' '), '', $buffer);
  8. return $buffer;
  9. }
  10. /* your css files */
  11. include('galleria.css');
  12. include('articles.css');
  13. ob_end_flush();
  14. ?>
复制代码

实例化: test.php

  1. test
复制代码

2. 压缩js 利用jsmin类 来源:http://code.google.com/p/minify/ compress.php

  1. header('Content-type: text/javascript');
  2. require 'jsmin.php';
  3. echo JSMin::minify(file_get_contents('common.js') . file_get_contents('common2.js'));
  4. ?>
复制代码

common.js alert('first js');

common.js alert('second js');

jsmin.php

  1. /**
  2. * jsmin.php - extended PHP implementation of Douglas Crockford's JSMin.
  3. *
  4. *
  5. * $minifiedJs = JSMin::minify($js);
  6. *
  7. *
  8. * This is a direct port of jsmin.c to PHP with a few PHP performance tweaks and
  9. * modifications to preserve some comments (see below). Also, rather than using
  10. * stdin/stdout, JSMin::minify() accepts a string as input and returns another
  11. * string as output.
  12. *
  13. * Comments containing IE conditional compilation are preserved, as are multi-line
  14. * comments that begin with "/*!" (for documentation purposes). In the latter case
  15. * newlines are inserted around the comment to enhance readability.
  16. *
  17. * PHP 5 or higher is required.
  18. *
  19. * Permission is hereby granted to use this version of the library under the
  20. * same terms as jsmin.c, which has the following license:
  21. *
  22. * --
  23. * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  24. *
  25. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  26. * this software and associated documentation files (the "Software"), to deal in
  27. * the Software without restriction, including without limitation the rights to
  28. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  29. * of the Software, and to permit persons to whom the Software is furnished to do
  30. * so, subject to the following conditions:
  31. *
  32. * The above copyright notice and this permission notice shall be included in all
  33. * copies or substantial portions of the Software.
  34. *
  35. * The Software shall be used for Good, not Evil.
  36. *
  37. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  42. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  43. * SOFTWARE.
  44. * --
  45. *
  46. * @package JSMin
  47. * @author Ryan Grove (PHP port)
  48. * @author Steve Clay (modifications + cleanup)
  49. * @author Andrea Giammarchi (spaceBeforeRegExp)
  50. * @copyright 2002 Douglas Crockford (jsmin.c)
  51. * @copyright 2008 Ryan Grove (PHP port)
  52. * @license http://opensource.org/licenses/mit-license.php MIT License
  53. * @link http://code.google.com/p/jsmin-php/
  54. */
  55. class JSMin {
  56. const ORD_LF = 10;
  57. const ORD_SPACE = 32;
  58. const ACTION_KEEP_A = 1;
  59. const ACTION_DELETE_A = 2;
  60. const ACTION_DELETE_A_B = 3;
  61. protected $a = " ";
  62. protected $b = '';
  63. protected $input = '';
  64. protected $inputIndex = 0;
  65. protected $inputLength = 0;
  66. protected $lookAhead = null;
  67. protected $output = '';
  68. /**
  69. * Minify Javascript
  70. *
  71. * @param string $js Javascript to be minified
  72. * @return string
  73. */
  74. public static function minify($js)
  75. {
  76. // look out for syntax like "++ +" and "- ++"
  77. $p = '\+';
  78. $m = '\-';
  79. if (preg_match("/([$p$m])(?:\1 [$p$m]| (?:$p$p|$m$m))/", $js)) {
  80. // likely pre-minified and would be broken by JSMin
  81. return $js;
  82. }
  83. $jsmin = new JSMin($js);
  84. return $jsmin->min();
  85. }
  86. /*
  87. * Don't create a JSMin instance, instead use the static function minify,
  88. * which checks for mb_string function overloading and avoids errors
  89. * trying to re-minify the output of Closure Compiler
  90. *
  91. * @private
  92. */
  93. public function __construct($input)
  94. {
  95. $this->input = $input;
  96. }
  97. /**
  98. * Perform minification, return result
  99. */
  100. public function min()
  101. {
  102. if ($this->output !== '') { // min already run
  103. return $this->output;
  104. }
  105. $mbIntEnc = null;
  106. if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
  107. $mbIntEnc = mb_internal_encoding();
  108. mb_internal_encoding('8bit');
  109. }
  110. $this->input = str_replace(" ", " ", $this->input);
  111. $this->inputLength = strlen($this->input);
  112. $this->action(self::ACTION_DELETE_A_B);
  113. while ($this->a !== null) {
  114. // determine next command
  115. $command = self::ACTION_KEEP_A; // default
  116. if ($this->a === ' ') {
  117. if (! $this->isAlphaNum($this->b)) {
  118. $command = self::ACTION_DELETE_A;
  119. }
  120. } elseif ($this->a === " ") {
  121. if ($this->b === ' ') {
  122. $command = self::ACTION_DELETE_A_B;
  123. // in case of mbstring.func_overload & 2, must check for null b,
  124. // otherwise mb_strpos will give WARNING
  125. } elseif ($this->b === null
  126. || (false === strpos('{[(+-', $this->b)
  127. && ! $this->isAlphaNum($this->b))) {
  128. $command = self::ACTION_DELETE_A;
  129. }
  130. } elseif (! $this->isAlphaNum($this->a)) {
  131. if ($this->b === ' '
  132. || ($this->b === " "
  133. && (false === strpos('}])+-"'', $this->a)))) {
  134. $command = self::ACTION_DELETE_A_B;
  135. }
  136. }
  137. $this->action($command);
  138. }
  139. $this->output = trim($this->output);
  140. if ($mbIntEnc !== null) {
  141. mb_internal_encoding($mbIntEnc);
  142. }
  143. return $this->output;
  144. }
  145. /**
  146. * ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
  147. * ACTION_DELETE_A = Copy B to A. Get the next B.
  148. * ACTION_DELETE_A_B = Get the next B.
  149. */
  150. protected function action($command)
  151. {
  152. switch ($command) {
  153. case self::ACTION_KEEP_A:
  154. $this->output .= $this->a;
  155. // fallthrough
  156. case self::ACTION_DELETE_A:
  157. $this->a = $this->b;
  158. if ($this->a === "'" || $this->a === '"') { // string literal
  159. $str = $this->a; // in case needed for exception
  160. while (true) {
  161. $this->output .= $this->a;
  162. $this->a = $this->get();
  163. if ($this->a === $this->b) { // end quote
  164. break;
  165. }
  166. if (ord($this->a)
  167. throw new JSMin_UnterminatedStringException(
  168. "JSMin: Unterminated String at byte "
  169. . $this->inputIndex . ": {$str}");
  170. }
  171. $str .= $this->a;
  172. if ($this->a === '\') {
  173. $this->output .= $this->a;
  174. $this->a = $this->get();
  175. $str .= $this->a;
  176. }
  177. }
  178. }
  179. // fallthrough
  180. case self::ACTION_DELETE_A_B:
  181. $this->b = $this->next();
  182. if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
  183. $this->output .= $this->a . $this->b;
  184. $pattern = '/'; // in case needed for exception
  185. while (true) {
  186. $this->a = $this->get();
  187. $pattern .= $this->a;
  188. if ($this->a === '/') { // end pattern
  189. break; // while (true)
  190. } elseif ($this->a === '\') {
  191. $this->output .= $this->a;
  192. $this->a = $this->get();
  193. $pattern .= $this->a;
  194. } elseif (ord($this->a)
  195. throw new JSMin_UnterminatedRegExpException(
  196. "JSMin: Unterminated RegExp at byte "
  197. . $this->inputIndex .": {$pattern}");
  198. }
  199. $this->output .= $this->a;
  200. }
  201. $this->b = $this->next();
  202. }
  203. // end case ACTION_DELETE_A_B
  204. }
  205. }
  206. protected function isRegexpLiteral()
  207. {
  208. if (false !== strpos(" {;(,=:[!&|?", $this->a)) { // we aren't dividing
  209. return true;
  210. }
  211. if (' ' === $this->a) {
  212. $length = strlen($this->output);
  213. if ($length
  214. return true;
  215. }
  216. // you can't divide a keyword
  217. if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
  218. if ($this->output === $m[0]) { // odd but could happen
  219. return true;
  220. }
  221. // make sure it's a keyword, not end of an identifier
  222. $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
  223. if (! $this->isAlphaNum($charBeforeKeyword)) {
  224. return true;
  225. }
  226. }
  227. }
  228. return false;
  229. }
  230. /**
  231. * Get next char. Convert ctrl char to space.
  232. */
  233. protected function get()
  234. {
  235. $c = $this->lookAhead;
  236. $this->lookAhead = null;
  237. if ($c === null) {
  238. if ($this->inputIndex inputLength) {
  239. $c = $this->input[$this->inputIndex];
  240. $this->inputIndex += 1;
  241. } else {
  242. return null;
  243. }
  244. }
  245. if ($c === " " || $c === " ") {
  246. return " ";
  247. }
  248. if (ord($c)
  249. return ' ';
  250. }
  251. return $c;
  252. }
  253. /**
  254. * Get next char. If is ctrl character, translate to a space or newline.
  255. */
  256. protected function peek()
  257. {
  258. $this->lookAhead = $this->get();
  259. return $this->lookAhead;
  260. }
  261. /**
  262. * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
  263. */
  264. protected function isAlphaNum($c)
  265. {
  266. return (preg_match('/^[0-9a-zA-Z_\$\\]$/', $c) || ord($c) > 126);
  267. }
  268. protected function singleLineComment()
  269. {
  270. $comment = '';
  271. while (true) {
  272. $get = $this->get();
  273. $comment .= $get;
  274. if (ord($get)
  275. // if IE conditional comment
  276. if (preg_match('/^\/@(?:cc_on|if|elif|else|end)\b/', $comment)) {
  277. return "/{$comment}";
  278. }
  279. return $get;
  280. }
  281. }
  282. }
  283. protected function multipleLineComment()
  284. {
  285. $this->get();
  286. $comment = '';
  287. while (true) {
  288. $get = $this->get();
  289. if ($get === '*') {
  290. if ($this->peek() === '/') { // end of comment reached
  291. $this->get();
  292. // if comment preserved by YUI Compressor
  293. if (0 === strpos($comment, '!')) {
  294. return " /*" . substr($comment, 1) . "*/ ";
  295. }
  296. // if IE conditional comment
  297. if (preg_match('/^@(?:cc_on|if|elif|else|end)\b/', $comment)) {
  298. return "/*{$comment}*/";
  299. }
  300. return ' ';
  301. }
  302. } elseif ($get === null) {
  303. throw new JSMin_UnterminatedCommentException(
  304. "JSMin: Unterminated comment at byte "
  305. . $this->inputIndex . ": /*{$comment}");
  306. }
  307. $comment .= $get;
  308. }
  309. }
  310. /**
  311. * Get the next character, skipping over comments.
  312. * Some comments may be preserved.
  313. */
  314. protected function next()
  315. {
  316. $get = $this->get();
  317. if ($get !== '/') {
  318. return $get;
  319. }
  320. switch ($this->peek()) {
  321. case '/': return $this->singleLineComment();
  322. case '*': return $this->multipleLineComment();
  323. default: return $get;
  324. }
  325. }
  326. }
  327. class JSMin_UnterminatedStringException extends Exception {}
  328. class JSMin_UnterminatedCommentException extends Exception {}
  329. class JSMin_UnterminatedRegExpException extends Exception {}
  330. ?>
复制代码

调用示例:

  1. <script type="text/javascript" src="fonts.php"></script>
复制代码


相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

616

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

194

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

91

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

20

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

54

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

29

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

15

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

598

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

56

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
独孤九贱(6)_jQuery视频教程
独孤九贱(6)_jQuery视频教程

共44课时 | 34.8万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号