1

the patern is like so

/* comment [comment goes here] */
/* comment please do not delete the lines below */
[I am a special line so I should not be changed ]
/* comment please do not delete the line above */

I would like to remove the comment blocks, but instead of looking for /**/ I would like the comment to be /* comment [] */ where [] is the actual comment.

This is to avoid any text that should include comments.

so here are the conditions of the comment

  1. starts with =>> /* comment
  2. followed by =>> anything
  3. followed by =>> */
2
  • How far have you tried ? Commented Mar 22, 2011 at 11:57
  • I have tried a few things, my regular expression knowledge is = to watching a monkey trying to figure out what his reflection is Commented Mar 22, 2011 at 11:59

2 Answers 2

3

This removes the comment blocks:

preg_replace('%/\*\s+comment\s+.*?\*/%s', '', $string)

And this get's rid of obsolete whitespace as well:

preg_replace('%/\s*\*\s+comment\s+.*?\*/\s*%s', '', $string)

Here's a test script:

#!/usr/bin/php
<?php

$string = <<<EOS
/* comment [comment goes here] */
/* comment please do not delete the lines below */
[I am a special line so I should not be changed ]
/* comment please do not delete the line above */
EOS;

print $string;
print "\n---\n";
print preg_replace('%/\*\s+comment\s+.*?\*/%s', '', $string);
print "\n---\n";
print preg_replace('%/\s*\*\s+comment\s+.*?\*/\s*%s', '', $string);

?>

Output with PHP 5.3.4:

/* comment [comment goes here] */
/* comment please do not delete the lines below */
[I am a special line so I should not be changed ]
/* comment please do not delete the line above */
---


[I am a special line so I should not be changed ]

---
[I am a special line so I should not be changed ]
Sign up to request clarification or add additional context in comments.

2 Comments

@val: What version of PHP are you using? Both snippets work as tested on PHP 5.3.4. (I've edited the answer and added a complete test script with output.)
@val: Sorry, I misinterpreted the square brackets in your question. Apparently, they are not part of the comment but you use them to mark the placeholder. I've fixed the patterns above accordingly.
0

Seems to do the job :)

preg_replace("(\\/\\*[\s]*?comment[\\d\\D]*?[\s]*?\\*\\/)",'',$str)

How I found out ?

well this website is just tooooo amazing :)

http://txt2re.com/index.php3

1 Comment

However, you can tell it's a generated expression. [\s]*?: The square brackets are obsolete and the question mark (greediness) as well as a character follows. [\\d\\D]*: This means "any digit or non digit", so it's equivalent to .*. It may work, but it's hard to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.