【问题标题】:Regular expression to remove CSS comments删除 CSS 注释的正则表达式
【发布时间】:2010-10-21 04:51:02
【问题描述】:

我想在 php 中编写正则表达式来匹配双引号和单引号内的行。实际上我正在编写用于删除 css 文件中的注释行的代码。

喜欢:

"/* I don't want to remove this line */"

但是

/* I want to remove this line */

例如:

- valid code /* comment */ next valid code "/* not a comment */" /* this is comment */

预期结果:

- valid code next valid code "/* not a comment */"

请任何人给我一个 php 中的正则表达式以满足我的要求。

【问题讨论】:

标签: php regex


【解决方案1】:

以下应该这样做:

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

测试用例:

$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 */" '

修订日期:2014 年 11 月 28 日

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

根据那篇文章,更新后的正则表达式是:

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

【讨论】:

  • 这与 css 规则末尾的通用 * 选择器有问题。例如.class &gt; *{}
  • @hexalys:感谢您的评论 - 我很想根据这些新信息修改我的答案。您能否通过 stackoverflow@lucanos.com 将受影响的 CSS 代码通过电子邮件发送给我,以便我进行一些测试并调整我的解决方案?
  • 您可以测试任何通用选择器。它可能与括号内的 cmets 有关,通常是这样。例如.class &gt; *{/*comments*/ } 我最终使用了the regex here
  • 更新的 2014 仍然匹配这个 -> li:before {content: "a/*b*/";}.
  • ^(\s*)\Q/*\E[\s\S]+?\Q*/\E$(\R+) 这将从行首 (^) 开始匹配,后跟零个或多个空格 ((\s*)) ...直到结束 ($) 与新行 ( (\R+))。它并不完美,但它只是为了防止匹配字符串内的注释。
猜你喜欢
  • 1970-01-01
  • 2011-01-28
  • 2012-05-20
  • 2012-04-08
  • 2011-05-11
  • 2020-09-30
  • 1970-01-01
  • 2011-04-01
相关资源
最近更新 更多