如何使用PHP删除JS注释?

时间:2013-10-22 05:44:51

标签: javascript php

如何使用PHP删除JS注释? 此问题已更新:2013年11月4日,回答人:Alexander Yancharuk 但是现在有一个问题。新代码:id = id.replace(/\//g,'');

这是我的例子:

<?php
$output = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(/\//g,''); //do not remove the regex //
";

$output = preg_replace( "/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:)\/\/.*))/", "", $output ); //Yancharuk's code/regex
// "/(?<!\:)\/\/(.*)\\n/ = my oldest code

echo nl2br($output);
?>

我的问题;

  1. this1行有问题;
  2. //注释正在运行,但我无法创建要删除的代码/ * 评论* /或带有换行符的评论
  3. 这是输出,最近:



    这个1 这2 这3 这4 this5 http://removecomment.com
    id = id.replace(/ \

7 个答案:

答案 0 :(得分:19)

试试这个:

$output = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(/\//g,''); //do not remove the regex //
HTTP+'//www.googleadservices.com/pagead/conversion'
";

$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\')\/\/.*))/';
$output = preg_replace($pattern, '', $output);

echo nl2br($output);

结果codepad.org

答案 1 :(得分:6)

Alexander Yancharuk的解决方案几近完美,他只是忘了忽略双引号,让他的答案在jquery.min.js上打破,其中包含代码:replace(Fb,yb [1] +“//”)

请在下面找到更正后的版本:

$output = "
//remove comment
this1 //remove comment
this2 /* remove comment */
this3 /* remove
comment */
this4 /* * * remove
* * * *
comment * * */
this5 http://removecomment.com
id = id.replace(/\//g,''); //do not remove the regex //
HTTP+'//www.googleadservices.com/pagead/conversion'
";

$pattern = '/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/';
$output = preg_replace($pattern, '', $output);

echo nl2br($output);

我使用它来基于Manas Tungare的CSS示例在PHP中创建一个流动的JS压缩:http://manas.tungare.name/software/css-compression-in-php/

<?php

/**
 * On-the-fly JS Compression by A. Heiligtag
 * Based on On-the-fly CSS Compression by  Manas Tungare.
 *
 * In order to minimize the number and size of HTTP requests for JS content,
 * this script combines multiple JS files into a single file and compresses
 * it on-the-fly.
 *
 */
$cssFiles = array(
    //<!-- Bootstrap -->
    // <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    "./js/jquery-1.11.3.min.js",
    // <!-- Bootstrap core JavaScript
    "./js/bootstrap.min.js",
    // <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    "./js/ie10-viewport-bug-workaround.js",

     // <!-- Jasny bootstrap -->
    "./js/jasny-bootstrap.min.js",

    // <!-- color picker : https://github.com/istvan-ujjmeszaros/bootstrap-colorpickersliders / http://www.virtuosoft.eu/code/bootstrap-colorpickersliders/ -->
    // <!-- ‘Polyglot’ Language Switcher 2 : http://www.ixtendo.com/polyglot-language-switcher-2/ -->
    "./js/jquery-polyglot.language.switcher.js"

);

/**
 * Ideally, you wouldn't need to change any code beyond this point.
 */
$buffer = "";
foreach ($cssFiles as $cssFile) {
  $buffer .= file_get_contents($cssFile);
}
// Remove comments
$buffer = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/', '', $buffer);
// Remove space after colons
$buffer = str_replace(': ', ':', $buffer);
// Remove space before equal signs
$buffer = str_replace(' =', '=', $buffer);
// Remove space after equal signs
$buffer = str_replace('= ', '=', $buffer);
// Remove whitespace
$buffer = str_replace(array("\r\n\r\n", "\n\n", "\r\r", '\t', '  ', '    ', '    '), '', $buffer);
// Enable GZip encoding.
ob_start("ob_gzhandler");
// Enable caching
header('Cache-Control: public');
// Expire in one day
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
// Set the correct MIME type, because Apache won't set it for us
header("Content-type: application/javascript");
// Write everything out
echo($buffer);
?>

答案 2 :(得分:1)

删除JavaScript评论和CDATA块(//<![CDATA[ , //]]>)合并alex的解决方案https://stackoverflow.com/a/8283600/2910183和Alexander的Yancharuk解决方案https://stackoverflow.com/a/19510664/2910183

$content = preg_replace('~//<!\[CDATA\[\s*|\s*//\]\]>~', '', $content);
$content = preg_replace('/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\)\/\/[^"\'].*))/', '', $content);

答案 3 :(得分:1)

这是我的最佳结果,在第一篇文章后搜索了许多网站, 这个函数适用于php中的javascript和css以及html内容

function _compress($html){
   //remove comments
   $html = preg_replace('|(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:)\/\/.*))|', '', $html ); //Yancharuk's code/regex

   // remove tabs, spaces, newlines, etc.
   $html = str_replace(array(PHP_EOL, "\t"), '', $html);

   //remove all spaces
   $html = preg_replace('|\s\s+|', ' ', $html);

   return $html;
}

答案 4 :(得分:0)

如果您想从客户端javascript代码中删除评论,那么您做错了。

只需使用minifier。除了删除注释之外,它将删除无意义的空格并缩短脚本中的所有名称。

例如github: UglifyJS 2

答案 5 :(得分:0)

复杂的正则表达式挂断!!! 使用简单的代码处理数千行

$module = preg_replace('/\/\*[^\/]*\*\//', '', $module);
/*
* remove comments like this 
*/

$module = preg_replace('/\/\*\*((\r\n|\n) \*[^\n]*)+(\r\n|\n) \*\//', '', $module);
/**
 * remove comments like this other method
 */
$module = preg_replace('/\n(\s+)?\/\/[^\n]*/', '', $module);
// remove comments like this
$module = preg_replace('/ (\t| )+/', '', $module); 
//double spaces
$module = preg_replace('/([\n])+/', "$1", $module);
//double newlines

答案 6 :(得分:-2)

我想分享一个正则表达式(PHP)的代码片段 我为自己写的它也被用在了 用于joomla的YIREO sriptmerge插件标记为简单代码.. 压缩javascript代码并从中删除所有注释。 它也适用于mootools它很快 (与其他PHP解决方案相比)并且不会损坏 它是自己的JavaScript,它解决了许多注释删除问题。

If you click on the link below you find a comment removal script in regex. 

这些是关闭代码的112行,它们可以与mootools和Joomla以及drupal和其他cms网站一起使用。 测试了800.000行代码和注释。工作良好。 这个也选择了多个括号(abc(/ nn /(&#39; / xvx /&#39;))&#34; //测试行&# 34;)和冒号之间的评论并保护它们。 23-01-2016 ..!这是带有注释的代码。!!!!

Click Here

我只是为了测试它的乐趣 (var regex=/(ftp|https?):\/\//;alert('hello,world');)和这个 /* foo(); // some comment */和此:"Python's division: 1 // 2" 这个//"you dope"例子 和我的压缩代码那些不会破坏上面的例子! 上述评论:( 使用正则表达式的愚蠢解析器会将有效的JavaScript代码视为注释!)所以也许你也可以用正则表达式编写没有愚蠢的解析器???

如果您找到了,请随时发表评论 这个脚本的问题与有效的javascript语句。任何一种 评论标签组合(或未组合),它没有正确解决..

更新后的需求不再需要测试800.000行正常工作。!