Carlos
Carlos

Reputation: 238

Remove comments from css file

I have to read a css file and remove its commentaries, so i've decided to use the preg_replace function from php:

$original = '
/*
foo
*/
.test, input[type="text"]{ color: blue; }

/* bar */
a:hover{
text-decoration: underline;
color: red;
background: #FFF;
}';

echo preg_replace('/\/\*.*\*\//s', '', $original);

the problem is that its losing the line .test, input[type="text"]{ color: blue; }

Upvotes: 0

Views: 1143

Answers (3)

Vijay Hardaha
Vijay Hardaha

Reputation: 2584

Try this:

$buffer = preg_replace('/\*[^*]*\*+([^/][^*]*\*+)*/', '', $buffer);

It doesn't work for //Comments here, but it works for the rest of /* Comment here */, even for multiple lines.

for //Comments here, use this one:

$buffer = preg_replace('/\/\*.*?\*\//s', '', $buffer);

Upvotes: 0

linden2015
linden2015

Reputation: 887

I would approach it as follows:

\/\*((?!\*\/).*?)\*\/


\/\*            # Start-of-comment
((?!\*\/).*?)   # Any character 0 or more times, lazy,
                #   without matching an end-of-comment
\*\/            # End-of-comment

Demo

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

Change .* to .*?.

echo preg_replace('#/\*.*?\*/#s', '', $original);

This will only remove /* up to the closest */ rather than the furthest.

Upvotes: 1

Related Questions