- preg_replace_callback: documentation ( source)
<?php
$string = <<<'STRING'
//single line comment
random text ... #another comment
Multiline comments:
/* this is a multiline comment
with 'squote and "dquote"
matches the whole thing */
// single line 'squoted' "dquoted" comment w/ extra " for no reason
More comments <!-- yatta yatta
yatta
yatta -->
Quotes:
"also matches strings with \" escaped quotes or 'the other kind of quotation marks in it' "
a "nested 'squote with nested \"dquote\"'" assuming only outermost quoting matters for formatting
'matches the end quote because it it not escaped \\'
STRING;
const PATTERN = <<<'PATTERN'
~(?|(")(?:[^"\\]|\\(?s).)*"|(')(?:[^'\\]|\\(?s).)*'|(#|//).*|(/\*)(?s).*?\*/|(<!--)(?s).*?-->)~
PATTERN;
const LOOKUP = [
'#' => 'gainsboro',
'//' => 'lightgrey',
'/*' => 'silver',
'<!--' => 'darkgrey',
"'" => 'mint',
'"' => 'aqua'
];
echo preg_replace_callback(PATTERN, function($m) {
return "<span style=\"color:" . LOOKUP[$m[1]] . ";\">{$m[0]}</span>";
}, $string);