Prettify Function using Google's Syntax Highlighter

This is the same function I use to syntax highlight all of my code at this site. There's a lot of syntax highlighters out there, but I settled on the google-code-prettify because it is lightweight, customizable, simple, and developed and used by Google themselves. As always, Internet Explorer did their best to screw up the code, and this function addresses the fix by prefixing every newline with ' ' (an XML friendly ' ') for you.

string prettify ( string $code [, string $lang [, bool or integer $linenum= false ]] )

This function will syntax highlight your code using google-code-prettify.

$code The code you want to syntax highlight.
$lang The language, if you want to specify it. This is completely optional. The avaliable values are 'bsh', 'c', 'cc', 'cpp', 'cs', 'csh', 'cyc', 'cv', 'htm', 'html', 'java', 'js', 'm', 'mxml', 'perl', 'pl', 'pm', 'py', 'rb', 'sh', 'xhtml', 'xml', and 'xsl'.
$linenum Set to true if you want the lines to be numbered. If your code doesn't begin on line 1 then you can indicate here where it does, and your code will be numbered accordingly.
Returns Your code in a <pre> tag that will be syntax highlighted when the page has loaded.
$html .= prettify('<?php  
echo 'Syntax Highlighted Code';  
Click to Download the PHP Prettify Function

 Subscribe to our feed


 *    author:		Kyle Gadd 
 *    documentation: 
 *    This program is free software: you can redistribute it and/or modify 
 *    it under the terms of the GNU General Public License as published by 
 *    the Free Software Foundation, either version 3 of the License, or 
 *    (at your option) any later version. 
 *    This program is distributed in the hope that it will be useful, 
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of 
 *    GNU General Public License for more details. 
 *    You should have received a copy of the GNU General Public License 
 *    along with this program.  If not, see <>. 
function prettify ($code, $lang='', $linenum=false) { 
  global $page; 
  $page->link(array('prettify.js', 'prettify.css')); 
  $html = '<pre class="prettyprint'; 
    if (!empty($lang) && in_array($lang, array('bsh', 'c', 'cc', 'cpp', 'cs', 'csh', 'cyc', 'cv', 'htm', 'html', 'java', 'js', 'm', 'mxml', 'perl', 'pl', 'pm', 'py', 'rb', 'sh', 'xhtml', 'xml', 'xsl'))) $html .= ' lang-' . $lang; 
  if ($linenum !== false) { 
    $html .= ' linenums'; 
    if (is_numeric($linenum)) $html .= ':' . $linenum; 
    $html .= '" style="padding-left:0px">'; 
  } else { 
    $html .= '">'; 
  $html .= str_replace(array('&', '<', '>', "\r\n", "\n"), array('&amp;', '&lt;', '&gt;', "\n", "&#160;\n"), trim($code)); 
  $html .= '</pre>'; 
  return $html; 

comments powered by Disqus
Copyright © 2011 - PHP Made Easy