简体   繁体   English

如何使用php从javascript文件中删除空格?

[英]How to remove spaces from javascript file using php?

I want to compress js files and convert into single line at the time of loading using php.when I removes the spaces with 'preg_replace' an error occurs, ';' 我想压缩js文件并在使用php加载时将其转换为单行。当我使用'preg_replace'删除空格时,发生错误';' missing in line 234. The cause is some lines are not ending with ';'.For eg 在第234行中缺少。原因是某些行未以';'结尾。例如

          var flag='value'  // here not ended with ';'
          var test='value';

And when I minifies, it looks like 当我缩小时,它看起来像

          var flag='value' var test='value';

So error occurs. 因此发生错误。

How can I minify js files with some lines not ending with ';' 如何缩小某些不以';'结尾的行的js文件

You would want to use a real parser based on the rules for automatic semi colon insertion . 您可能希望使用基于自动半冒号插入规则的真实解析器。

Otherwise if you do (ie use a regex)... 否则,如果您这样做(即使用正则表达式)...

$str = preg_replace('/(?<!;)\s*(\n|\z)/', ";$1", $str);

...you are going to munch valid JavaScript, eg ...您将使用有效的JavaScript,例如

var a = 'a',
    b = 'bob';

...which will become... ...将成为...

var a = 'a',;
    b = 'bob';

CodePad . 键盘

There are plenty of existing JavaScript packers/minifiers . 有很多现有的JavaScript包装器/压缩器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM