正则表达式删除CSS注释

use*_*146 5 php regex

我想在php中编写正则表达式,以匹配双引号和单引号中的行.其实我正在编写用于删除css文件中的注释行的代码.

喜欢:

"/* I don't want to remove this line */"
Run Code Online (Sandbox Code Playgroud)

/* I want to remove this line */
Run Code Online (Sandbox Code Playgroud)

例如:

- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */
Run Code Online (Sandbox Code Playgroud)

预期结果:

- valid code next valid code "/* not a comment */"
Run Code Online (Sandbox Code Playgroud)

请任何人根据我的要求在PHP中给我一个正则表达式.

Luk*_*son 14

以下应该这样做:

preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $theString );
Run Code Online (Sandbox Code Playgroud)

测试用例:

$theString = '- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */';

preg_replace( '/(?!<\")\/\*[^\*]+\*\/(?!\")/' , ' ' , $theString );

# Returns 'valid code next valid code "/* not a comment */" '
Run Code Online (Sandbox Code Playgroud)

修订:2014年11月28日

根据@hexalys的评论,他们提到了http://www.catswhocode.com/blog/3-ways-to-compress-css-files-using-php

根据该文章,更新的正则表达式是:

preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!' , '' , $theString );
Run Code Online (Sandbox Code Playgroud)