当前位置:Gxlcms > PHP教程 > 压缩多个CSS与JS文件的php代码

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

时间:2021-07-01 10:21:17 帮助过:25人阅读

  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) <= self::ORD_LF) {
  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) <= self::ORD_LF) {
  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("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
  209. return true;
  210. }
  211. if (' ' === $this->a) {
  212. $length = strlen($this->output);
  213. if ($length < 2) { // weird edge case
  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 < $this->inputLength) {
  239. $c = $this->input[$this->inputIndex];
  240. $this->inputIndex += 1;
  241. } else {
  242. return null;
  243. }
  244. }
  245. if ($c === "\r" || $c === "\n") {
  246. return "\n";
  247. }
  248. if (ord($c) < self::ORD_SPACE) { // control char
  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) <= self::ORD_LF) { // EOL reached
  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 "\n/*" . substr($comment, 1) . "*/\n";
  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. ?>

调用示例:

人气教程排行