3v4l.org

run code in 200+ php & hhvm versions
<?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);
based on vVjuO
Output for 7.1.25 - 7.3.4
<span style="color:lightgrey;">//single line comment</span> random text ... <span style="color:gainsboro;">#another comment</span> Multiline comments: <span style="color:silver;">/* this is a multiline comment with 'squote and "dquote" matches the whole thing */</span> <span style="color:lightgrey;">// single line 'squoted' "dquoted" comment w/ extra " for no reason</span> More comments <span style="color:darkgrey;"><!-- yatta yatta yatta yatta --></span> Quotes: <span style="color:aqua;">"also matches strings with \" escaped quotes or 'the other kind of quotation marks in it' "</span> a <span style="color:aqua;">"nested 'squote with nested \"dquote\"'"</span> assuming only outermost quoting matters for formatting <span style="color:mint;">'matches the end quote because it it not escaped \\'</span>