转换单行注释以阻止注释 [英] Convert Single Line Comments To Block Comments

查看:121
本文介绍了转换单行注释以阻止注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换单行注释(// ...)阻止注释(/*...*/)。我几乎在下面的代码中完成了这个;但是,我需要该函数跳过任何单行注释已经在块注释中。

I need to convert single line comments (//...) to block comments (/*...*/). I have nearly accomplished this in the following code; however, I need the function to skip any single line comment is already in a block comment. Currently it matches any single line comment, even when the single line comment is in a block comment.

 ## Convert Single Line Comment to Block Comments
 function singleLineComments( &$output ) {
  $output = preg_replace_callback('#//(.*)#m',
   create_function(
     '$match',
     'return "/* " . trim(mb_substr($match[1], 0)) . " */";'
   ), $output
  );
 }


推荐答案

code> // ... 可能出现在块注释和字符串文字内部。因此,如果你使用regex-trickery的aid位创建一个小的解析器,你可以先匹配这些东西(字符串文字或块评论),然后测试 / /...。

As already mentioned, "//..." can occur inside block comments and string literals. So if you create a small "parser" with the aid f a bit of regex-trickery, you could first match either of those things (string literals or block-comments), and after that, test if "//..." is present.

这是一个小演示:

$code ='A
B
// okay!
/*
C
D
// ignore me E F G
H
*/
I
// yes!
K
L = "foo // bar // string";
done // one more!';

$regex = '@
  ("(?:\\.|[^\r\n\\"])*+")  # group 1: matches double quoted string literals
  |
  (/\*[\s\S]*?\*/)          # group 2: matches multi-line comment blocks
  |
  (//[^\r\n]*+)             # group 3: matches single line comments
@x';

preg_match_all($regex, $code, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);

foreach($matches as $m) {
  if(isset($m[3])) {
    echo "replace the string '{$m[3][0]}' starting at offset: {$m[3][1]}\n";
  }
}

产生以下输出:

replace the string '// okay!' starting at offset: 6
replace the string '// yes!' starting at offset: 56
replace the string '// one more!' starting at offset: 102

当然,在PHP中可能有更多的字符串文字,假设。

Of course, there are more string literals possible in PHP, but you get my drift, I presume.

HTH。

这篇关于转换单行注释以阻止注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆