如何删除注释行以//开头,而不是像http://使用preg_replace的URL

I need to remove the comment lines from my code.

preg_replace('!//(.*)!', '', $test);

It works fine. But it removes the website url also and left the url like http:

So to avoid this I put the same like preg_replace('![^:]//(.*)!', '', $test);

It's work fine. But the problem is if my code has the line like below

$code = 'something';// comment here

It will replace the comment line with the semicolon. that is after replace my above code would be

$code = 'something'

So it generates error.

I just need to delete the single line comments and the url should remain same.

Please help. Thanks in advance

try this

preg_replace('@(?<!http:)//.*@','',$test);

also read more about PCRE assertions http://cz.php.net/manual/en/regexp.reference.assertions.php

If you want to parse a PHP file, and manipulate the PHP code it contains, the best solution (even if a bit difficult) is to use the Tokenizer : it exists to allow manipulation of PHP code.


Working with regular expressions for such a thing is a bad idea...

For instance, you thought about http:// ; but what about strings that contain // ?
Like this one, for example :

$str = "this is // a test";

This can get complicated fast. There are more uses for // in strings. If you are parsing PHP code, I highly suggest you take a look at the PHP tokenizer. It's specifically designed to parse PHP code.

Question: Why are you trying to strip comments in the first place?

Edit: I see now you are trying to parse JavaScript, not PHP. So, why not use a javascript minifier instead? It will strip comments, whitespace and do a lot more to make your file as small as possible.