javascript 如何使用 PHP 删除 JS 注释?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19509863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:50:10  来源:igfitidea点击:

How to remove JS comments using PHP?

javascriptphp

提问by Momar

How to remove JS comments using PHP? This question is updated: Nov. 4 2013 and answered by: Alexander Yancharuk But there is a problem right now. A new code: id = id.replace(/\//g,'');

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

This is my example:

这是我的例子:

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

My Problems;

我的问题;

  1. Something wrong with the this1 line;
  2. The //comments is working but I can't create a codes to remove /* comment */ or by that comment with a line break
  1. this1 行有问题;
  2. //comments 正在工作,但我无法创建代码来删除 /* 注释 */ 或该注释与换行符

Here is the output, recent:

这是最近的输出:



this1
this2
this3
this4
this5 http://removecomment.com
id = id.replace(/\



this1
this2
this3
this4
this5 http://removecomment.com
ID = id.replace(/ \

回答by Alexander Yancharuk

Try this:

试试这个:

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

Result on codepad.org.

codepad.org 上的结果。

回答by AmaelH

Alexander Yancharuk solution is nearly perfect, he just forgot to ignore double quotes, making his answer break on jquery.min.js which contains the code : replace(Fb,yb[1]+"//")

Alexander Yancharuk 解决方案几乎是完美的,他只是忘记忽略双引号,使他的答案在包含代码的 jquery.min.js 上中断:replace(Fb,yb[1]+"//")

Please find below the corrected version :

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

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

I used this to create a on-the-flow JS compression in PHP based on Manas Tungare example for CSS : http://manas.tungare.name/software/css-compression-in-php/

我用它基于 CSS 的 Manas Tungare 示例在 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);
?>

回答by Кирилл Сабуров

Complex regexp hangs up!!! Use simple ones for work with thousands of lines

复杂的正则表达式挂了!!!使用简单的来处理数千行

$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])+/', "", $module);
//double newlines

回答by Ebrahim

This is my best result, following the first post and searching many sites, this function well works for javascript and css and html content in php

这是我最好的结果,在第一篇文章之后搜索了很多网站,这个功能很好地适用于 javascript 和 css 以及 php 中的 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;
}

回答by Bart?omiej Jakub Kwiatek

To remove JavaScript comments and CDATA blocks (//<![CDATA[ , //]]>)combine alex's soluton https://stackoverflow.com/a/8283600/2910183and Alexander's Yancharuk solution https://stackoverflow.com/a/19510664/2910183:

要删除JavaScript注释和CDATA块(//<![CDATA[ , //]]>)结合alex的soluton https://stackoverflow.com/a/8283600/2910183和亚历山大的Yancharuk解决方案https://stackoverflow.com/a/19510664/2910183

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

回答by Waterlink

If you want to remove comments from your client side javascript code then you doing it wrong.

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

Just use minifier. On top of removing comments, it will remove meaningless whitespaces and shorten all names in script.

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

For example github: UglifyJS 2

例如github:UglifyJS 2

回答by John Smith

I would like to share a regex (PHP) snippet of code I wrote for myself it is also being used in the YIREO sriptmerge plugin for joomla marked as simple code.. To compress javascript code and remove all comments from it. It also works with mootools It is fast (in comparison to other PHP solutions) and does not damage the JavaScript it self and it resolves lots of comment removal issues.

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

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

These are 112 lines off code that work together also works with mootools and Joomla and drupal and other cms websites. Tested it on 800.000 lines of code and comments. works fine. This one also selects multiple parenthetical like ( abc(/nn/('/xvx/'))"// testing line") and comments that are between colons and protect them. 23-01-2016..! This is the code with the comments in it.!!!!

这些是 112 行的代码,可以与 mootools 和 Joomla 以及 drupal 和其他 cms 网站一起工作。在 800.000 行代码和注释上对其进行了测试。工作正常。这个还选择了多个括号,如 (abc(/ nn/('/ xvx/'))"// testing line") 和冒号之间的注释并保护它们。23-01-2016..!这是带有注释的代码。!!!

Click Here

点击这里

I have just for the fun of it tested this (var regex=/(ftp|https?):\/\//;alert('hello,world');) and this /* foo(); // some comment */and this: "Python's division: 1 // 2"and this //"you dope"example and my compression code those not damage the example above! COMMENT FROM ABOVE:( A stupid parser that uses regular expressions will treat valid JavaScript code as comments!) So Maybe you can also write none stupid parsers with regex???

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

Please feel free to leave a comment if you find a problem with this script with valid javascript sentences. And any kind of comments tags combined (or not combined) that it does not solve correctly..

如果您发现此脚本有问题且带有有效的 javascript 语句,请随时发表评论。以及任何类型的评论标签组合(或未组合)它不能正确解决..

Updated needs no more testing 800.000 lines work fine now.!

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