开发者

How to remove spaces from javascript file using php?

开发者 https://www.devze.com 2023-02-21 03:40 出处:网络
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,\';\' missing in line 234.

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, ';' missing in line 234. The cause is some lines are not ending with ';'.For eg

          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 ';'


You would want to use a real parser based on the rules for automatic semi colon insertion.

Otherwise if you do (i.e. use a regex)...

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

...you are going to munch valid JavaScript, e.g.

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

...which will become...

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

CodePad.

There are plenty of existing JavaScript packers/minifiers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号