4

ReGex newbie here.

I need to remove two different style comments from PHP files using RegEx.

I've found this expression to run in the BBEdit text editor:

\/\*[\s\S]*?\*\/

and it removes comments in the first style, like below:

/** This comment gets removed with my regex */

But it doesn't remove these style comments:

// ** This comment has the double leadng-trailng slashes ** //

I don't know why there is a mix of the two different types of comments, and there are only a few of the // comments, but I need to delete them all.

Adding another slash to the search, i.e.

\/\\*[\s\S]*?\*\/

makes the expression greedy and it removes single slashes in non-commented code. A working expression will require obviously more complexity than that :)

markratledge
  • 17,013
  • 11
  • 57
  • 104

3 Answers3

5

PHP has got a built-in function for that:

php_strip_whitespace($filename);
jeroen
  • 90,003
  • 21
  • 112
  • 129
  • 2
    This is excellent, I provided an answer based on regex but +1 because you used a built-in function. – Federico Piazza Sep 01 '14 at 17:45
  • A php function solution is good to know and I may use it in the future; but I need to run the regex in BBedit to clean a file that is being opened and edited. And, strip_whitespace removes all whitespace and compacts the code too much for clean editing. – markratledge Sep 01 '14 at 19:55
  • @FedericoPiazza since you love this answer, why not write a php script: and call it like this: http://localhost/stripwhite.php?file=myfile.php – Popsyjunior Apr 27 '17 at 09:15
2

You can use this regex:

\/\*.*?\*\/|\/\/.*?\n

Working demo

enter image description here

As Hwnd pointed in this answer, if you change the delimiter to ~ you can use the cleaned regex:

/\*.*?\*/|//.*?\n
Community
  • 1
  • 1
Federico Piazza
  • 28,830
  • 12
  • 78
  • 116
1
~//?\s*\*[\s\S]*?\*\s*//?~

This works.Just added another \ and space eaters to your answer.

See demo.

http://regex101.com/r/lK9zP6/6

hwnd
  • 67,942
  • 4
  • 86
  • 123
vks
  • 65,133
  • 10
  • 87
  • 119
  • This works great. And regex101 is a great site to play around with regex; I didn't know about it before. Thanks. – markratledge Sep 01 '14 at 19:56
  • @songdogtech yes it is.Youare welcome.There's one https://www.debuggex.com/ as well.To visualise . – vks Sep 01 '14 at 19:58