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');