2011-03-22 65 views
1

的百通是像这样PHP的preg_replace注释块

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

我想删除注释块,但不是找/**/我想评论是/* comment [] */,其中[]是实际的评论。

这是为了避免任何应该包含注释的文本。

所以这里的评论,随后=条件

  1. 开始与= >>/* comment
  2. 其次= >>什么
  3. >>*/
+0

多远你试过吗? – codaddict 2011-03-22 11:57:47

+0

我已经尝试了几件事,我的正则表达知识是=看一只猴子试图弄清楚他的反射是什么 – Val 2011-03-22 11:59:22

回答

3

这消除评论区块:

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

这GET的摆脱陈旧的空白,以及:

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

这是一个测试脚本:

#!/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); 

?> 

输出与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 ] 
+0

似乎没有工作 – Val 2011-03-22 12:07:24

+0

[编辑]两者都不工作 – Val 2011-03-22 12:20:28

+0

@val:什么版本你在用PHP吗?这两个片段都在PHP 5.3.4上测试。 (我编辑了答案并添加了一个完整的测试脚本和输出。) – svoop 2011-03-22 14:57:44

0

似乎做的工作:)

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

我怎么知道的?

以及这个网站只是tooooo惊人:)

http://txt2re.com/index.php3

+0

但是,您可以告诉它是生成的表达式。 '[\ s] *?':方括号已经过时,问号(贪婪)以及字符如下。 '[\\ d \\ D] *':这意味着“任何数字或非数字”,所以它相当于'。*'。它可能工作,但很难阅读。 – svoop 2011-03-22 15:12:26