Core PHP

Coloring Comments with Regular Expressions

This PHP example program demonstrates how to color comments with regular expressions.

ColorComments.php

<?php

// Code to load the program file and style the comments
$sCppProgramFileName = "main.cpp";
$saCppProgramFile = file($sCppProgramFileName);
$sCppProgram = "";
$bInsideComment = false;
foreach($saCppProgramFile as $sNextLine) {
  // Check for three typs of comments; start, end, and to the end of the line.
  $sNextLine = htmlspecialchars($sNextLine, ENT_QUOTES | ENT_HTML5);
  $sNextLine = str_replace('$', '&dollar;', $sNextLine);
  $sNextLine = preg_replace('/\/\*/', '<span class="comments">/*', $sNextLine);
  $sNextLine = preg_replace('/\*\//', '*/</span>', $sNextLine);
  $sNextLine = preg_replace('/\/\/(.*)(\r\n)/',
  	'<span class="comments">//\1</span>\2', $sNextLine);
  $sCppProgram .= $sNextLine;
}

echo "<!DOCTYPE html><html>";
echo "<head>
<style type=\"text/css\">
.comments {
    color: Red;
}
</style>";
echo "</head>";
echo "<body>";
echo "<pre>".$sCppProgram."</pre>";
echo "</body>";
echo "</html>";
?>
 

main.cpp

#include <iostream>
#include <fstream>

int main() {
  std::cout << "Writing to the file . . ." << std::endl;

  // We will create an output file stream so that we can open it for writing.
  std::ofstream qTextFile;
  // Create a new file or write over an old one.
  qTextFile.open("Virtues.txt");
  /* Write the four cardinal virtues to it.*/
  qTextFile << "Fortitude" << std::endl;
  qTextFile << "Prudence" << std::endl;
  qTextFile << "Justice" << std::endl;
  qTextFile << "Temperance" << std::endl;
  qTextFile.close();
  return 0;
}

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.