0

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; }

0

3 Answers 3

1

Change .* to .*?.

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Like a charm. Thanks for the fast and precise answer. May i ask, why the interrogation is matching the closest? I mean, its a '0 or 1 ocurrences' match isn't it?
0

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.