0
嘿朋友。我有以下代碼來使用PHP來縮小JavaScript。它的工作是刪除評論和空白空間......但它刪除了評論,並用一個新行替換它們,即 \ n 但是當我嘗試用''替換\ n時,JavaScript給了我一個編譯器錯誤刪除評論使用PHP縮小JavaScript
我知道有很多是PHP庫來縮小,但我需要我自己
這裏是PHP代碼中,我有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');
看一看:http://stackoverflow.com/questions/11000261/how-to-minify-js-in-php-easily-or-something-else 不要嘗試和創建自己的縮小器,當已經有很好的開源替代品時,這是浪費時間 –
人們總是會告訴你不要重新發明輪子......你說**你需要你自己的minifyer ** - 你能解釋一下嗎? *以防止這些類型的評論? – Lix
@Lix因爲我想了解其他人是如何做到這一點的 –