Removing block comments via Regex

I am struggling to get this regex to work. All I'm trying to do is delete block comments. This is what I still have, but I can’t get rid of the final */ .

 $string = 'this is a test /*asdfa */ ok then'; $pattern = '/\/\*([^\*\/]*)/i'; $replacement = ''; echo preg_replace($pattern, $replacement, $string); //this is a test */ ok then 

Any help would be appreciated.

+7
php regex
source share
7 answers

Use a different delimiter than / - it confuses.

What about '#/\*.+?\*/#s' ;

+6
source share

token_get_all and return it without T_COMMENT s. I don’t think anything else can be said.

+6
source share

Try this as your template:

/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/

+4
source share

I use this (note that you only need the first line for comments /*...*/ ):

  #-- extract /* ... */ comment block # or lines of #... #... and //... //... if (preg_match("_^\s*/\*+(.+?)\*+/_s", $src, $uu) or (preg_match("_^\s*((^\s*(#+|//+)\s*.+?$\n)+)_ms", $src, $uu))) { $src = $uu[1]; } // Public Domain, not CC 

It works well. But, like all regular expression solutions, it will fail in the case of the $PHP = "st/*rings" edge.

+1
source share

Running preg_replace twice with the pattern /\*|\*/ should work.

0
source share

May be:

 $pattern = '/\/\*([.]*)\*\//i'; 

Please do not slow down, as this is a quick guess, trying to help ... :)

0
source share

To fix the main template, I can say that you do not agree with the final "* /" because you are missing it from your template.

Following your template, try this small modification:

'/\/\*([^\*\/]*)**\*\/**/i'

I also suggest that you use different separators to make the template more readable.

#/\*([^\*/]*)\*/#i

0
source share

All Articles