Jump to content


Photo

Regex to match PHP comments


  • Please log in to reply
1 reply to this topic

#1 linux_pickle

linux_pickle
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 29 August 2006 - 12:48 AM

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

#2 linux_pickle

linux_pickle
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 29 August 2006 - 01:13 AM

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

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

(from http://www.perl.com/...gular_expressio)

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

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

Again, anyone's help would be greatly appreciated!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users