简体   繁体   中英

php preg_replace comment blocks

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 =>> */

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 ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM