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
);
}
To comment out multiple code lines right-click and select Source > Add Block Comment. ( CTRL+SHIFT+/ ) To uncomment multiple code lines right-click and select Source > Remove Block Comment. ( CTRL+SHIFT+\ )
There is no difference whatsoever. All comments are removed so at execution comments don't impact the program, regardless of their format. It's a matter of convenience.
// Single-line comments The comment begins with a double slash (//) and ends at a newline character (\n), a carriage return (\r), or the end of the file.
Using multiple single # line comments to add a block comment in Python. The most common way to comment out a block of code in Python is using the # character. Any line of code starting with # in Python is treated as a comment and gets ignored by the compiler.
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.
Here's a small demo:
$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";
}
}
Which produces the following output:
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
Of course, there are more string literals possible in PHP, but you get my drift, I presume.
HTH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With