Have you ever wanted to post code on your site and have it appear nicely formatted with syntax highlighting? It couldn't be easier.

Using the native PHP highlight_string() function, it's easy to create a form to do the work for you. Be sure to precede your input code with <?php, or the function will not add syntax highlighting. While the function is designed to format PHP, I've found that it works well for most other languages as well. If you want to get more involved, you can dive into PEAR's Text_Highlighter, which provides a high degree of control over the formatting options.

This example uses the HTTP Request wrapper found here, Smarty, FCKEditor, and Gazoot's Smarty FCKEditor plugin. If you aren't already using Smarty, you can just splat the output back to the screen in the PHP. Safari users: FCKEditor does not currently run in Safari, hopefully this will change in the near future. Jump to Firefox for the full-on FCK experience.


The PHP:
<?php
require_once("lib/request.php");
require_once(
'lib/smarty.php');

$request = new Request();

$input $request->getParameter("input");
$output = ($input=='') ? '':'<div class="code">'.highlight_string($inputtrue).'</div>';

$smarty->assign('input'$input);
$smarty->assign('output'$output);
$smarty->display('code_format.tpl');


The Smarty template:
<html>
<
head>
<
title>Code Formatter</title>
<
link rel="stylesheet" href="/css/style.css">
</
head>
<
body>
<
form method="post">
<
div>
    <
textarea rows="20" cols="80" name="input">{$input}</textarea>
</
div>
<
input type="submit" name="button_submit" value="Format">
<
div>
{
fckeditor BasePath="FCKeditor/" InstanceName="output" Width="100%" Height="300px"
 
ToolbarSet="code" Value=$output}
</
form>
</
body>
</
html>


CSS for code box:
.code
{
      
background-color#F6F6F6;
      
border1px solid #666;
      
margin-top5px;
      
padding5px;
}

Give it a shot: