删除特定CSS注释的PHP正则表达式
我想在下面的php匹配条件下编写正则表达式:删除特定CSS注释的PHP正则表达式,php,regex,preg-replace,Php,Regex,Preg Replace,我想在下面的php匹配条件下编写正则表达式: /* Remove this comment line 1 Remove this comment line 2 */ .class1 { background:#CCC url(images/bg.png); } .class2 { color: #FFF; background:#666 url(images/bg.png); /* DON'T re
/*
Remove this comment line 1
Remove this comment line 2
*/
.class1
{
background:#CCC url(images/bg.png);
}
.class2
{
color: #FFF;
background:#666 url(images/bg.png); /* DON'T remove this comment */
}
/* Remove this comment */
.class3
{
margin:2px;
color:#999;
background:#FFF; /* DON'T Remove this comment */
}
...etc
...etc
请任何人给我一个php正则表达式。谢谢。如果规则是要删除行中没有其他代码的所有注释,那么类似的操作应该可以:
/^(\s*\/\*.*?\*\/\s*)$/m
“m”选项使^和$匹配行的开头和结尾。您是否希望注释可以运行多行
编辑:
我很确定这符合要求:
/(^|\n)\s*\/\*.*?\*\/\s*/s
你明白它在做什么吗?代码板:
支持多行:
/* Remove this comment
multi-lane style 1*/
/* Remove this comment
multi-lane style 2
*/
/* Remove this comment */
正则表达式解释:
^ Start of line
\s* only contains whitespace
\/\* continue with /*
[^(\*\/)]* unlimited number of character except */ includes newline
\*\/ continue with */
m pattern modifier (makes ^ start of line, $ end of line
php代码示例:
$regex = "/^\s*\/\*[^(\*\/)]*\*\//m";
$newstr = preg_replace($regex,"",$str);
echo $newstr;
不适用于多行注释,如
/*
* Lorem ipsum
*/
这一个就行了
$regex = "!/\*[^*]*\*+([^/][^*]*\*+)*/!";
$newstr = preg_replace($regex,"",$str);
echo $newstr;
在这里找到:为什么不删除所有评论?实际上:/(^\124n)\s*/*.*?*/\s*(\n ^$)/s
/\n\s*/.*?*/\s*.\n/s
和/(^\124n)\s*/.*?*/\s*(\n\$)/s
对我不起作用,@Godwin。使用preg_replace时产生一些错误。很抱歉,我认为在剪切和粘贴时出现了一些问题。检查原始答案中的编辑。谢谢,它在一行注释中工作,多行注释如何。例如:/*******第1行第2行第3行******/