开发者

Removing Block Comments via Regex

I am having difficulty trying to get this regex to work. All I am trying to do is remove block comments. This is what I have so far 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 will be appreciated.


Use a different delimiter than / -- it makes it confusing.

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


token_get_all and build it back without T_COMMENTs. I don't think anything more should be said.


Try this as your pattern:

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


I'm using 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

Works quite well. But like all regex solutions, it would fail on the $PHP = "st/*rings" edge case.


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


To just fix your main pattern, I can tell you that your not matching the final "*/" because you are missing it from your pattern.

Following your own pattern, try this little modification:

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

I also suggest you to use different delimitators to make the pattern more read-friendly.

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


Maybe:

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

Please don't down-rate as this is a quick guess trying to help... :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜