我必须阅读一个css文件并删除它的评论,所以我决定使用php中的preg_replace
函数:
$original = '
/*
foo
*/
.test, input[type="text"]{ color: blue; }
/* bar */
a:hover{
text-decoration: underline;
color: red;
background: #FFF;
}';
echo preg_replace('/\/\*.*\*\//s', '', $original);
问题在于它丢失了行.test, input[type="text"]{ color: blue; }
答案 0 :(得分:1)
将.*
更改为.*?
。
echo preg_replace('#/\*.*?\*/#s', '', $original);
这只会删除/*
最近的*/
而不是最远的{{1}}。
答案 1 :(得分:0)
我会按如下方式处理:
\/\*((?!\*\/).*?)\*\/
\/\* # Start-of-comment
((?!\*\/).*?) # Any character 0 or more times, lazy,
# without matching an end-of-comment
\*\/ # End-of-comment
答案 2 :(得分:0)
尝试一下:
$buffer = preg_replace('/\*[^*]*\*+([^/][^*]*\*+)*/', '', $buffer);
它不适用于//Comments here
,但它适用于/* Comment here */
的其余部分,甚至适用于多行。
对于//Comments here
,请使用以下命令:
$buffer = preg_replace('/\/\*.*?\*\//s', '', $buffer);