RegEx to remove /** */ and // ** **// php comments

我与影子孤独终老i 提交于 2019-12-18 08:49:20

问题


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


回答1:


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

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

See demo.

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




回答2:


PHP has got a built-in function for that:

php_strip_whitespace($filename);



回答3:


You can use this regex:

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

Working demo

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

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


来源:https://stackoverflow.com/questions/25610603/regex-to-remove-and-php-comments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!