1

Hey friends. I have the following code to minify JavaScript using PHP. Its work is to remove comments and white space .... but it removes comments and replace them with a new line that is \n but when I tried to replace \n with '' then JavaScript gave me a compiler error how to remove comments

I Know there's is many PHP libraries to minify but I need my own

here is the PHP code I have com.php

function compress_js($buffer){      
$replace = array(
"/\/\*[\s\S]*?\*\//" => '',//remove nultile line comment
"/\/\/.*$/" => '',//remove single line comment
'#[\r\n]+#'   => "\n",// remove blank lines and \r's
'#\n([ \t]*//.*?\n)*#s'   => "\n",// strip line comments (whole line only)
'#([^\\])//([^\'"\n]*)\n#s' => "\\1\n",
'#\n\s+#' => "\n",// strip excess whitespace
'#\s+\n#' => "\n",// strip excess whitespace
'#(//[^\n]*\n)#s' => "\\1\n", // extra line feed after any comments left
);

$search = array_keys( $replace );
$script = preg_replace( $search, $replace, $buffer );
$replace = array(
"&&\n" => '&&',
'|| ' => '||',
"(\n"  => '(',
")\n"  => ')',
"[\n"  => '[',
"]\n"  => ']',
"+\n"  => '+',
",\n"  => ',',
"?\n"  => '?',
":\n"  => ':',
";\n"  => ';',
"{\n"  => '{',
"\n]"  => ']',
"\n)"  => ')',
"\n}"  => '}',
' ='  => '=',
'= '  => '=',
"\n\n" => ' ',
'if (' => 'if(',
' || ' => '||'
);
$search = array_keys($replace);
$script = str_replace( $search, $replace, $script );
$script = str_replace(';}', '}',$script);
return  $script;
}

ob_start('compress_js');
header('Content-type: text/javascript');

readfile('foo.js');
fzzle
  • 1,466
  • 5
  • 23
  • 28
  • 3
    Take a look at: http://stackoverflow.com/questions/11000261/how-to-minify-js-in-php-easily-or-something-else Don't try and create your own minifier, it's a waste of time when there are already good opensource alternatives – Marco de Jongh May 07 '14 at 11:56
  • People are always going to tell you not to re-invent the wheel... You say that **you need your own minifyer** - could you perhaps explain *why* so as to prevent these types of comments? – Lix May 07 '14 at 12:15
  • @Lix Because I Wanted To Learn How other people did this magic – Navneet Kumar May 07 '14 at 12:17
  • To detect wether your current position in the code is minifiable and which rules to apply you need to keep state. What you have is a simple set of right-linear grammars (a.k.a reg exps or L3). You need a context sensitive grammar (a minor form of a parser). – mwhs May 07 '14 at 12:52

1 Answers1

0

As everybody says you'd better prefer normal solutions for this stuff because it's tricky. Although if you just need to echo a few lines of javascript through php and you have to minify it you are doing fine!

Just add :

return preg_replace( "/\r|\n/", "", $script);

to the end of your function.

Kostas
  • 140
  • 1
  • 13