Highlight Source Code in Your PHP Application

Share this article

If you run a Website about programming, chances are that you display source code on your site’s pages. Wouldn’t it be great if the source code was highlighted — displayed using different colors — in the same way the desktop programming editors and IDEs display it? This would certainly make it much easier for your visitors to read the code.

This tutorial explains how you can highlight source code shown on your Website for a number of programming languages without manually formatting and hand-coding the display.

I’ll show how to highlight source code in two ways:

  1. Using the PHP’s built-in highlighter for PHP source code

  2. Using PEAR’s Text_Highlighter package to highlight the source code for virtually any programming or markup language

This tutorial forms a sequel to my previous article, titled Use BB Code in Your PHP Application, and it uses the same setup for the code environment. While this article doesn’t assume you’ve read the previous one, you might want to take a look at the Setup section of it.

Using PHP’s Built-in Source Highlighter

PHP offer two functions for highlighting PHP code: highlight_file() and highlight_string(). Both functions return the same results, but each has its own specific input parameters. As their names suggest, the first function takes the filename of the PHP script whose code is to be highlighted, while the second takes the input as a string.

A Quick Example

Let’s take a look at an example of the highlight_string() function in action:

<?php 
include_once 'init.inc.php';

if (!empty($_POST['text'])){
   
   echo '<div style="border: solid 1px orange; padding: 20px; margin: 20px">';
   highlight_string($_POST['text']);
   echo '</div>';
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
   <textarea name="text" style="width: 300px; height: 200px"><?php  
       echo @$_POST['text'];  
   ?></textarea>
   <br />
   <input type="submit" />
</form>

This script displays a simple textbox into which you can type or paste the PHP code you want to highlight. The code for the example is available in this article’s code archive and a live demo is available online. The purpose of the init.inc.php file required at the beginning of the script was explained in the Setup section of my previous article.

Here’s a screenshot of the script in action.

1468_image1

As you can see, the highlighted version of the code is much clearer and easier to follow than the standard black-and-white code.

Color Customization

The PHP highlighter uses the following colors to display the code:

1468_table1

The identifiers in the first column are actually the names of PHP configuration directives. This means that you can customize the highlight colors by altering the PHP configuration. So, if you want your keywords to be pink for a change (not pretty, I know, but this is just an example), you can do so by using a simple .htaccess file, containing:

php_value highlight.keyword #ff00ff

Drawbacks of the Native PHP Method

As you can see, this method of highlighting PHP source code is very easy to use, gives great results, and is customizable. However, it has some downsides:

  • It will work properly on PHP source code only. Sometimes you can get somewhat acceptable results when highlighting other programming code, like HTML or JavaScript, but most times, the results won’t be very good. This is simply because these highlight functions were designed specifically for PHP code.
  • The resulting HTML code, after the highlighting is performed, is not XHTML-compliant. This issue is corrected in PHP5, but in PHP4, the highlighter uses the <font> tag, something that is considered almost a crime by today’s Web coders.
Using PEAR: Say Hello to the Text_Highlighter Package

In its repository of PHP libraries, PEAR has a special package for highlighting source code. It’s called Text_Highlighter, and its details, documentation and downloads are available online.

This package features:

  • The ability to highlight the source code for 12 different programming languages
  • Extensiblility; the package allows you to define more languages using a simple XML file
  • Line numbering and tab size options are available
  • The ability to highlight code in the console window
  • Output is provided in XHTML format, using <span> tags for semantics and CSS styles for formatting

A Few Words on the Setup

To prepare your system to run the following examples:

  1. Install the PEAR core libraries

  2. Install the Text_Highlighter package

  3. Set up your environment, a.k.a. copy my 10-line init.inc.php file

These steps were described in detail in the previous article and are not hard to do. Don’t be scared of the word “install” here: it’s basically just a “copy” operation. The setup doesn’t require you to have any special privileges on the server, and is easily done in low-cost shared hosting environments. If you want to see the directory structure of an example setup, browse the code examples from this article.

Usage

Once you’ve finished the setup, you can start using the highlighter. In order to highlight the PHP source code contained in, let’s say, $some_source_code variable, all you need to do is:

  1. Include the class definition:
    require_once 'Text/Highlighter.php';
  2. Create an object of the class:
    $highlighter =& Text_Highlighter::factory('php');
  3. Call the highlighting method and print the output:
    echo $highlighter->highlight($some_source_code);

Test the Highlighter

Here’s a simple script that you can use to test the highlighter package:

<?php 
include_once 'init.inc.php';

if (!empty($_POST['text'])){
   
   echo '<link rel="stylesheet" href="hilight.css" />';
   echo '<div style="border: solid 1px orange; padding: 20px; margin: 20px">';
   
   require_once 'Text/Highlighter.php';
   $highlighter =& Text_Highlighter::factory('php');
   echo $highlighter->highlight($_POST['text']);
   
   echo '</div>';
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
   <textarea name="text" style="width: 300px; height: 200px"><?php echo @$_POST['text']; ?></textarea>
   <br />
   <input type="submit" />
</form>

Here’s a screenshot of the script in action.

1468_image2

You can play around with a live demo here.

Colors of the Rainbow

As you can see, the PEAR highlighter is working a lot like the built-in PHP highlighter we looked at first. The only visible difference from the previous example is in the number of colors: there are seven here, rather than the three we saw in the first example. This is made possible because the PEAR highlighter is more granular when it comes to the “ingredients” of the source code.

If you view the source of the result of the script above, you’ll see that the highlighting places <span class="hl-something"> tags around the different source code elements. The CSS class names, such as hl-xxxx, need to be defined in order for the coloring to be displayed.

You can take a peek at the CSS file used in the example above if you wish. As you can see, 18 style definitions are used in the CSS file, 15 of which are related to the different elements you might find in a source code file: variables, strings, brackets, quotes, etc. The CSS definitions give you the power to customize the colors used for highlighting as you find appropriate.

It’s Not All PHP!

So far, all the examples have focused on coloring PHP code. But what if your site isn’t about PHP? Tough luck, some might think, but not the Text_Highlighter package, which offers a colorful hand to 11 other programming and markup languages, including C++, CSS, JavaScript, XML (also used for HTML files), to name a few.

To highlight the code of another language, just change the ‘php’ in the below line to reflect the language of your choice:

$highlighter =& Text_Highlighter::factory('php');

Want to highlight CSS?

$highlighter =& Text_Highlighter::factory('css');

You can now highlight a CSS stylesheet.

Here’s a full list of the language identifiers you can use when creating the highlighter object:

  • 'cpp'
  • 'css'
  • 'diff'
  • 'dtd'
  • 'javascript'
  • 'mysql'
  • 'perl'
  • 'php'
  • 'python'
  • 'ruby'
  • 'sql'
  • 'xml'

You can use this live demo to see how other languages are colored. The source file is available in this article’s code archive.

As a side note: you’ve probably noticed already that an object of the highlighter class is created using its factory() method. This is a popular object-oriented technique (an OO pattern). Although an understanding the inner workings of the factory pattern is not required for this article, you can still find out more if you’re interested; this PHPPatterns entry is a good starting point.

Fine Tuning the Highlighter

In addition to coloring, the highlighter can:

  • Display line numbers along with the source code
  • Use different tab sizes to indent code

The first feature can be activated in two ways: using a numbered list (<ol>) or an HTML table. In the latter case, you can use CSS to define a style for the column that contains the numbers, which is different than the one containing the source code.

These options are passed as an array with keys:

  • 'numbers': This setting accepts the following values:
    • 0: the default value, meaning no numbering is used
    • HL_NUMBERS_LI: an ordered listing will be used
    • HL_NUMBERS_TABLE: the code will be displayed in a table

  • 'tabsize': This option takes an integer value. It sets how many &nbsp; will be used to replace a tab.

If you choose the table option, you can use the following CSS selectors to customize the look of the table:

  • h1-main – for the row with the source code
  • hl-gutter – the numbering row
  • hl-table – the whole table

Take a look at this article’s stylesheet for an example. The three CSS selectors mentioned above can be found at the bottom of the stylesheet.

A sample options array will look like this:

    $options = array( 
           'numbers' => HL_NUMBERS_TABLE,
           'tabsize' => 4,
       );

Setting the Options

There are two ways to set the options for highlighting:

  1. The easy way: just add the options to the factory method. This is the simpler method in terms of syntax, but it exists only for backwards-compatibility purposes.
    $highlighter =& Text_Highlighter::factory('php', $options);

  2. The proper way: use the renderer object.

As mentioned above, in addition to the browser, the highlighter can also color code in the console window. In the future new display devices, like PDAs, phones, your beloved iPod or (last, but not least) your kitchen sink may also be supported — who knows? To allow for this type of forward-compatibility, the display part of the work is passed to renderer objects. So far, two renderers exist: HTML and Console. All you need to do is create a renderer object, then pass it to the highlighter. Here’s how:

    require_once 'Text/Highlighter.php'; 
   require_once 'Text/Highlighter/Renderer/Html.php';

   $options = array(
           'numbers' => HL_NUMBERS_TABLE,
           'tabsize' => 4,
       );
   
   $renderer =& new Text_Highlighter_Renderer_HTML($options);
   $highlighter =& Text_Highlighter::factory('php');
   $highlighter->setRenderer($renderer);
   echo $highlighter->highlight($_POST['text']);

The full source code listing is available in this article’s code archive. A live demo using the HTML renderer and tables to display the source code is also available. Here’s a screenshot of the script in action.

1468_image3

Other Options

Here are some other options you might want to take a look at that are not covered in this article.

  • GeSHi: Generic Syntax Highlighter – a non-PEAR highlighter package, currently supporting 35 programming languages.
  • Aidan Lister’s PHP repository contains two classes that use and extend the native PHP coloring. The first class adds line numbers and makes the PHP functions into links to the PHP manual. The second does the same, but in its own way, without the use of the native PHP functions. It also produces XHTML output and can optionally use a stylesheet for color definitions.
  • Enscript is a command line tool for syntax highlighting. An example use of it is this WordPress plugin.
Summary

In this article, we discussed in detail two ways to highlight source code in your PHP application. If you want to quickly colorize come PHP code, make a call or two to the native highlighting functions that are built into the language. Or, if you want to highlight more languages and have more display options, consider installing a copy of the PEAR’s Text_Highlighter package.

You now have a basic knowledge of how to use color coding to enhance the readability of Web pages that contain source code, and improve your visitors’ experience.

Frequently Asked Questions about Highlighting Source Code in PHP

How can I highlight source code in PHP?

PHP has a built-in function called highlight_string() that can be used to highlight source code. This function returns a syntax-highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP. You can use this function by passing the PHP code as a string to the function. For example, highlight_string(‘‘); will return a syntax-highlighted version of the phpinfo() function.

What are the benefits of highlighting source code in PHP?

Highlighting source code in PHP can make the code easier to read and understand. It can help you identify syntax errors more quickly, and it can also make it easier to debug your code. Additionally, if you’re sharing your code with others, highlighting can make it more readable and easier for others to understand.

Can I customize the colors used by the highlight_string() function?

Yes, you can customize the colors used by the highlight_string() function by using the ini_set() function to set the ‘highlight.*’ configuration options. For example, you can set the color for keywords, strings, comments, and other elements of the PHP syntax.

How can I highlight source code in PHP without using the highlight_string() function?

If you want to highlight source code in PHP without using the highlight_string() function, you can use a library or a tool like GeSHi or Pygments. These tools support multiple programming languages and offer more customization options than the built-in PHP function.

Can I use the highlight_string() function to highlight code in other programming languages?

No, the highlight_string() function is designed to highlight PHP code. If you want to highlight code in other programming languages, you can use a library or a tool like GeSHi or Pygments, which support multiple programming languages.

How can I display the highlighted code in a web page?

The highlight_string() function returns a string with the highlighted code, which you can then display in a web page. You can use the echo statement to print the string, or you can include it in the HTML code of your page.

Can I save the highlighted code to a file?

Yes, you can save the highlighted code to a file by using the file_put_contents() function. This function writes a string to a file. You can pass the string returned by the highlight_string() function to the file_put_contents() function to save the highlighted code to a file.

Can I highlight source code in PHP on the command line?

Yes, you can highlight source code in PHP on the command line by using the -r option followed by the code you want to highlight. For example, php -r ‘highlight_string(““);’ will highlight the phpinfo() function and print the highlighted code to the console.

How can I highlight source code in PHP in a text editor or an IDE?

Most text editors and IDEs have built-in support for syntax highlighting. You can usually enable or customize syntax highlighting in the settings or preferences of your text editor or IDE. Some text editors and IDEs also support plugins or extensions that can add or improve syntax highlighting.

Can I use the highlight_string() function to highlight HTML code in PHP?

No, the highlight_string() function is designed to highlight PHP code. If you want to highlight HTML code, you can use a library or a tool that supports HTML, like GeSHi or Pygments.

Stoyan StefanovStoyan Stefanov
View Author

Stoyan is an engineer at Yahoo and the author the author of Object-Oriented JavaScript and other books and articles about web development. Outside work, his time is spent experimenting with random web technologies, blogging at phpied.com and playing the blues guitar to his daughters' despite their preference for Mickey Mouse CDs.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week