Compress PHP code for multiple CSS and JS files

Source: Internet
Author: User
    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 ("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. ?>
Copy Code

Instantiation: test.php

    1. Test
Copy Code

2. Compressing JS using Jsmin class Source: 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. ?>
Copy Code

Common.jsalert (' first JS ');

Common.jsalert (' 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 was 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 is preserved, as is multi-line
  14. * Comments that begin with "/*!" (For documentation purposes). In the latter case
  15. * Newlines is 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 all 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 are furnished to do
  30. * So, subject to the following conditions:
  31. *
  32. * The above copyright notice and this permission notice shall is included in all
  33. * Copies or substantial portions of the software.
  34. *
  35. * The software shall is 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 a 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 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'll 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 a 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 the 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 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. ?>
Copy Code

Invocation Example:

Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.