如何使用PHP

时间:2015-05-01 12:04:31

标签: javascript php minify

我想删除这些脚本中的注释:

var stName = "MyName"; //I WANT THIS COMMENT TO BE REMOVED
var stLink = "http://domain.com/mydomain";
var stCountry = "United State of America";

使用PHP实现此目的的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

最好的方法是使用实​​际的解析器或至少自己写一个词法分析器 正则表达式的问题在于,如果考虑到必须考虑的因素,它会变得非常复杂 例如,Cagatay Ulubay建议的正则表达式/\/\/[^\n]?//\/\*(.*)\*\//会匹配评论,但它们也会匹配更多内容,例如

var a = '/* the contents of this string will be matches */';
var b = '// and here you will even get a syntax error, because the entire rest of the line is removed';
var c = 'and actually, the regex that matches multiline comments will span across lines, removing everything between the first "/*" and here: */';
/*
   this comment, however, will not be matched.
*/

虽然字符串不太可能包含这样的序列,但内联正则表达式存在问题:

var regex = /^something.*/; // You see the fake "*/" here?

当前范围很重要,除非你从头开始解析脚本,否则你不可能知道当前的范围。
所以你基本上需要建立一个词法分析器 您需要将代码分成三个不同的部分:

  • 普通代码,您需要再次输出,以及评论的开头可能只有一个字符。
  • 你放弃的评论。
  • 文字,您还需要输出,但注释无法启动。

现在我能想到的唯一文字是字符串(单引号和双引号),内联正则表达式和模板字符串(反引号),但那些可能不是全部。
当然,您还必须考虑这些文字中的转义序列,因为您可能会遇到内联正则表达式,如

/^file:\/\/\/*.+/

其中基于单字符的词法分析器只会看到正则表达式/^file:\/,并错误地将以下/*.+解析为多行注释的开头。
因此,在遇到第二个/时,您必须回顾并检查您传递的最后一个字符是否为\。对于字符串的各种引号也是如此。

答案 1 :(得分:0)

我会选择preg_replace()。假设所有评论都是单行评论(//评论在这里),您可以从这开始:

$JsCode = 'var stName = "MyName isn\'t \"Foobar\""; //I WANT THIS COMMENT TO BE REMOVED
var stLink = "http://domain.com/mydomain"; // Comment
var stLink2 = \'http://domain.com/mydomain\'; // This comment goes as well
var stCountry = "United State of America"; // Comment here';

$RegEx = '/(["\']((?>[^"\']+)|(?R))*?(?<!\\\\)["\'])(.*?)\/\/.*$/m';
echo preg_replace($RegEx, '$1$3', $JsCode);

输出:

var stName = "MyName isn't \"Foobar\""; 
var stLink = "http://domain.com/mydomain"; 
var stLink2 = 'http://domain.com/mydomain'; 
var stCountry = "United State of America"; 

此解决方案远非完美,可能存在包含&#34; //&#34;的字符串问题。在他们中间。

相关问题