4 * This is a minification script. It minifies the desired script "in-place"
6 * Usage (Unix): ./minify file1 file2 ...
7 * Usage (Windows): C:\php\php.exe minify file1 file2 ...
9 * The minification is medium, and it can over halve a scripts size.
10 * Combined with subsequent gzip compression the results can be excellent. For
11 * example a 70k script of mine was reduced to just 7k. (!) Substantial
12 * bandwidth savings for you, and much improved performance for your users.
14 * NOTE: Usage on Windows works, but is less tested
20 if (empty($_SERVER['argv'][1])) {
21 echo "RGraph minification script\n";
22 echo "==========================\n";
23 echo "Usage (Unix): " . $_SERVER['argv'][0] . " file1 file2 ...\n";
24 echo "Usage (Windows): C:\php\php.exe " . $_SERVER['argv'][0] . " file1 file2 ...\n\n";
29 for ($i=1; $i<count($_SERVER['argv']); ++$i) {
30 Minify($_SERVER['argv'][$i]);
36 * This is the function that does the work of minifying the file
38 * @param $filename string The filename to be minified
40 function Minify($filename)
45 $original = file_get_contents($filename);
46 $new = preg_replace('/^ +/m', '', $original); // Lose spaces at the start of lines
47 $new = preg_replace('/ *\/\/.*$/m', '', $new); // Lose comments of the style: "// ..."
48 $new = preg_replace("/;\r?\n/m", ";\r\n", $new); // Make all lines end with \r\n
49 //$new = preg_replace("|\r\n\*|", "", $new);
52 * Get rid of block comments
55 $inBlock = false; // Are we in a block comment
56 for ($i=0; $i<strlen($new); $i++) {
57 if (substr($new, $i, 1) == '/') {
59 if (!$inBlock AND substr($new, $i, 2) == '/*') {
62 } elseif (substr($new, $i, 2) == '*/') {
69 $out .= substr($new, $i, 1);
74 * Get rid of double line breaks
76 * NOTE: Is this necessary?
78 $out = preg_replace('|\n+|', "\n", $out);
82 * UPDATED: 28th March 2009 - Line endings have been changed - they should all be \r\n
84 $out = str_replace(";\r\n}", ';}', $out);
85 $out = str_replace(";\r\nRGraph", ';RGraph', $out);
86 $out = preg_replace('/;\r\n([a-z])/i', ';$1', $out);
87 $out = str_replace('if (', 'if(', $out);
88 $out = str_replace(') {', '){', $out);
89 $out = str_replace("}\r\n", '}', $out);
90 $out = str_replace("{\r\n", '{', $out); // UPDATED
91 $out = str_replace("{\r\n", '{', $out); // UPDATED
92 $out = str_replace("}\r\n}", '}}', $out); // UPDATED
93 $out = str_replace("}\r\n}", '}}', $out); // UPDATED
94 $out = str_replace("}\r\n}", '}}', $out); // UPDATED
95 $out = preg_replace('/ {2,}= /', ' = ', $out);
97 // Mark the file as minified
98 $out = "// THIS FILE HAS BEEN MINIFIED\r\n" . $out;
100 file_put_contents($filename, $out);
102 printf(" Minifying {$filename} Before: %s After: %s Saving: %d%%\n", number_format(strlen($original)), number_format(strlen($out)), number_format((((strlen($original) - strlen($out)) / strlen($original)) * 100), 1));