【问题标题】:php preg_replace comment blocksphp preg_replace 注释块
【发布时间】:2011-07-20 10:22:56
【问题描述】:

模式是这样的

/* 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 [] */,其中[] 是实际评论。

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

所以这里是评论的条件

  1. 以 =>> /* comment 开头
  2. 接着 =>> 任何东西
  3. 随后是 =>> */

【问题讨论】:

  • 你尝试了多远?
  • 我已经尝试了一些东西,我的正则表达式知识是=看着一只猴子试图弄清楚他的反射是什么

标签: php preg-replace comments


【解决方案1】:

这将删除评论块:

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

这也消除了过时的空白:

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 ]

【讨论】:

  • @val:您使用的是什么版本的 PHP?两个 sn-ps 都可以在 PHP 5.3.4 上测试。 (我已经编辑了答案并添加了带有输出的完整测试脚本。)
  • @val:对不起,我误解了你问题中的方括号。显然,它们不是评论的一部分,但您使用它们来标记占位符。我已经相应地修复了上面的模式。
【解决方案2】:

似乎完成了这项工作:)

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

我是怎么知道的?

这个网站太棒了:)

http://txt2re.com/index.php3

【讨论】:

  • 但是,你可以看出它是一个生成的表达式。 [\s]*?:方括号已过时,后面是问号(贪婪)和一个字符。 [\\d\\D]*:这意味着“任何数字或非数字”,所以它相当于.*。它可能有效,但很难阅读。
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 2011-01-30
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2010-10-17
相关资源
最近更新 更多