欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-18 09:38:32
...
  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("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $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 = "\n";
  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("\r\n", "\n", $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 === "\n") {
  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 === "\n"
  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) throw new JSMin_UnterminatedStringException(
  167. "JSMin: Unterminated String at byte "
  168. . $this->inputIndex . ": {$str}");
  169. }
  170. $str .= $this->a;
  171. if ($this->a === '\\') {
  172. $this->output .= $this->a;
  173. $this->a = $this->get();
  174. $str .= $this->a;
  175. }
  176. }
  177. }
  178. // fallthrough
  179. case self::ACTION_DELETE_A_B:
  180. $this->b = $this->next();
  181. if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
  182. $this->output .= $this->a . $this->b;
  183. $pattern = '/'; // in case needed for exception
  184. while (true) {
  185. $this->a = $this->get();
  186. $pattern .= $this->a;
  187. if ($this->a === '/') { // end pattern
  188. break; // while (true)
  189. } elseif ($this->a === '\\') {
  190. $this->output .= $this->a;
  191. $this->a = $this->get();
  192. $pattern .= $this->a;
  193. } elseif (ord($this->a) throw new JSMin_UnterminatedRegExpException(
  194. "JSMin: Unterminated RegExp at byte "
  195. . $this->inputIndex .": {$pattern}");
  196. }
  197. $this->output .= $this->a;
  198. }
  199. $this->b = $this->next();
  200. }
  201. // end case ACTION_DELETE_A_B
  202. }
  203. }
  204. protected function isRegexpLiteral()
  205. {
  206. if (false !== strpos("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
  207. return true;
  208. }
  209. if (' ' === $this->a) {
  210. $length = strlen($this->output);
  211. if ($length return true;
  212. }
  213. // you can't divide a keyword
  214. if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
  215. if ($this->output === $m[0]) { // odd but could happen
  216. return true;
  217. }
  218. // make sure it's a keyword, not end of an identifier
  219. $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
  220. if (! $this->isAlphaNum($charBeforeKeyword)) {
  221. return true;
  222. }
  223. }
  224. }
  225. return false;
  226. }
  227. /**
  228. * Get next char. Convert ctrl char to space.
  229. */
  230. protected function get()
  231. {
  232. $c = $this->lookAhead;
  233. $this->lookAhead = null;
  234. if ($c === null) {
  235. if ($this->inputIndex inputLength) {
  236. $c = $this->input[$this->inputIndex];
  237. $this->inputIndex += 1;
  238. } else {
  239. return null;
  240. }
  241. }
  242. if ($c === "\r" || $c === "\n") {
  243. return "\n";
  244. }
  245. if (ord($c) return ' ';
  246. }
  247. return $c;
  248. }
  249. /**
  250. * Get next char. If is ctrl character, translate to a space or newline.
  251. */
  252. protected function peek()
  253. {
  254. $this->lookAhead = $this->get();
  255. return $this->lookAhead;
  256. }
  257. /**
  258. * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
  259. */
  260. protected function isAlphaNum($c)
  261. {
  262. return (preg_match('/^[0-9a-zA-Z_\\$\\\\]$/', $c) || ord($c) > 126);
  263. }
  264. protected function singleLineComment()
  265. {
  266. $comment = '';
  267. while (true) {
  268. $get = $this->get();
  269. $comment .= $get;
  270. if (ord($get) // if IE conditional comment
  271. if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  272. return "/{$comment}";
  273. }
  274. return $get;
  275. }
  276. }
  277. }
  278. protected function multipleLineComment()
  279. {
  280. $this->get();
  281. $comment = '';
  282. while (true) {
  283. $get = $this->get();
  284. if ($get === '*') {
  285. if ($this->peek() === '/') { // end of comment reached
  286. $this->get();
  287. // if comment preserved by YUI Compressor
  288. if (0 === strpos($comment, '!')) {
  289. return "\n/*" . substr($comment, 1) . "*/\n";
  290. }
  291. // if IE conditional comment
  292. if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  293. return "/*{$comment}*/";
  294. }
  295. return ' ';
  296. }
  297. } elseif ($get === null) {
  298. throw new JSMin_UnterminatedCommentException(
  299. "JSMin: Unterminated comment at byte "
  300. . $this->inputIndex . ": /*{$comment}");
  301. }
  302. $comment .= $get;
  303. }
  304. }
  305. /**
  306. * Get the next character, skipping over comments.
  307. * Some comments may be preserved.
  308. */
  309. protected function next()
  310. {
  311. $get = $this->get();
  312. if ($get !== '/') {
  313. return $get;
  314. }
  315. switch ($this->peek()) {
  316. case '/': return $this->singleLineComment();
  317. case '*': return $this->multipleLineComment();
  318. default: return $get;
  319. }
  320. }
  321. }
  322. class JSMin_UnterminatedStringException extends Exception {}
  323. class JSMin_UnterminatedCommentException extends Exception {}
  324. class JSMin_UnterminatedRegExpException extends Exception {}
  325. ?>
复制代码

调用示例:

复制代码