roy*_*key 6 php regex comments
我需要将单行注释转换(//...)为块注释(/*...*/).我在下面的代码中几乎完成了这个; 但是,我需要函数来跳过任何单行注释已经在块注释中.目前,它匹配任何单行注释,即使单行注释位于块注释中.
## 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
);
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试负面观察:http ://www.regular-expressions.info/lookaround.html
## Convert Single Line Comment to Block Comments
function sinlgeLineComments( &$output ) {
$output = preg_replace_callback('#^((?:(?!/\*).)*?)//(.*)#m',
create_function(
'$match',
'return "/* " . trim(mb_substr($match[1], 0)) . " */";'
), $output
);
}
Run Code Online (Sandbox Code Playgroud)
但是我担心其中可能包含 // 的字符串。就像:$x =“某个字符串//带斜杠”;会得到转变。
如果您的源文件是 PHP,您可以使用 tokenizer 来更精确地解析文件。
http://php.net/manual/en/tokenizer.examples.php
编辑: 忘记了固定长度,您可以通过嵌套表达式来克服该固定长度。上面的内容现在应该可以工作了。我用以下方法测试了它:
$foo = "// this is foo";
sinlgeLineComments($foo);
echo $foo . "\n";
$foo2 = "/* something // this is foo2 */";
sinlgeLineComments($foo2);
echo $foo2 . "\n";
$foo3 = "the quick brown fox";
sinlgeLineComments($foo3);
echo $foo3. "\n";;
Run Code Online (Sandbox Code Playgroud)