Jump to content

Regex to match PHP comments


linux_pickle

Recommended Posts

I've been using PHP for a long time, but I am a beginner with Regexes.
I need a regex that will match any kind of PHP comment (/**/, //, #) because I am trying to write a script that will use preg_replace to remove all comments from a PHP file.

I have searched the web for a solution, but to no avail. >:(

Any help would be greatly appreciated,

linux_pickle
Link to comment
Share on other sites

Oops, forgot to mention that I found one regex on the perl site that looked hopeful:

s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;

(from [url=http://www.perl.com/doc/manual/html/pod/perlfaq6.html#How_do_I_use_a_regular_expressio]http://www.perl.com/doc/manual/html/pod/perlfaq6.html#How_do_I_use_a_regular_expressio[/url])

Here is my PHP code:
[code]
// Clean comments
$comment_regex = '{/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|\'(\\.|[^\'\\])*\'|.[^/"\'\\]*)}';
$infile_contents = preg_replace($comment_regex, '', $infile_contents);
[/code]

When I put in the regex, I escaped the single quotes (as you can see above), but after doing that I got this error:
[code]Warning: preg_replace(): Compilation failed: missing terminating ] for character
class at offset 77 in test.php on line 65[/code]???

Again, anyone's help would be greatly appreciated!
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.