The easiest way to highlight PHP syntax

What do you think is the easiest way to highlight PHP syntax? Well it can be done by mere one line code. Most of the people are not aware of this technique. You don't need to install any third party module or script for this. Did you know that PHP by default provides an in-built function for syntax highlighting!?  Well apparently its true! 

PHP provides two built in functions - highlight_string() and highlight_file() which you can use for PHP syntax highlighting. The highlight_string() function takes string as an argument and similarly highlight_file() function takes filename as an argument. Here I will use highlight_string() function for syntax highlighting purpose. The string is highlighted by using HTML tags. Lets say we have a sample PHP code snippet that we have to highlight as shown below.

<?php

echo 'This is the first line';

echo 'Well another additional line';

echo 'Followed by a third line';

?>

Create a file named syntax_highlighter.php and add the following in it:

<html>
<head>
<title>PHP Syntax Highlighter</title>
</head>
<body>
<?php

$string = "<?php

echo 'This is the first line';

echo 'Well another additional line';

echo 'Followed by a third line';

?>";

highlight_string($string);

?>

</body>
</html> 

Run this file and you will get the following output:

PHP Syntax Highlighter

 

As you can see the output is properly formatted and highlighted! Isn't it cool?

The colors used for highlighting can be changed/set in the php.ini file or with the ini_set() function.

Advanced PHP Syntax Highlighter with line number

Here is a custom PHP function which you can use instead of default highlight_string() and it will print line numbers also.

<?php

function custom_highlighter($string)
{
  $Line = explode("\n",$string);
  for($i=1;$i<=count($Line);$i++)
  {
   $line .= "&nbsp;".$i."&nbsp;<br>";
  }
  ob_start();
  highlight_string($string);
  $Code=ob_get_contents();
  ob_end_clean();

  $header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
   <tr>
     <td width="100%" colspan="2"  style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
  </tr>
   <tr>
     <td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'.$line.'</code></td>
     <td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>';
  $footer=$Code.'</div></code></td>
   </tr>
  </table>';
  return $header.$footer;
}
?>

See the cool output below!

PHP Syntax Highlighter

Tags: