Home » Php » php – Removing Block Comments via Regex

php – Removing Block Comments via Regex

Posted by: admin July 12, 2020 Leave a comment


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.

How to&Answers:

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:



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 also suggest you to use different delimitators to make the pattern more read-friendly.




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

Please don’t down-rate as this is a quick guess trying to help… 🙂