Reputation: 57916
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.
Upvotes: 7
Views: 2946
Reputation: 833
Maybe:
$pattern = '/\/\*([.]*)\*\//i';
Please don't down-rate as this is a quick guess trying to help... :)
Upvotes: 0
Reputation: 106530
Use a different delimiter than /
-- it makes it confusing.
How about '#/\*.+?\*/#s'
;
Upvotes: 6
Reputation: 145482
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.
Upvotes: 1
Reputation: 221
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
Upvotes: 0
Reputation: 3685
Running preg_replace
twice with pattern /\*|\*/
should work.
Upvotes: 0
Reputation: 12269
Try this as your pattern:
/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/
Upvotes: 6
Reputation: 44346
token_get_all and build it back without T_COMMENT
s. I don't think anything more should be said.
Upvotes: 6