Highlight Code In PHP

12th January 2008 - 2 minutes read time

When printing off source code there is a handy function that will parse the code and produce nice looking syntax highlighted code. There are actually two functions you can use. The highlight_string() function takes a string as a parameter and will print the highlighted code. The highlight_file() function takes a file name as a parameter, the contents of which are printed off with highlighted syntax. For now I will concentrate on the highlight_string() function, but the output of these two functions is the same.

To use the highlight_string() function just pass it a string. The following code:

  1. highlight_string('<?php
  2. function checkslash($slashes_string){
  3. if (get_magic_quotes_gpc()==1) {
  4. return $slashes_string;
  5. }else{
  6. return addslashes($slashes_string);
  7. };
  8. };
  9. ?>');

Will produce the following output:

highlight_string() function example

How the code is highlighted depends on your version of PHP. In all cases the code is highlighted using HTML, but it is the syntax that changes. In PHP 4 the main HTML tag used is font. Running the code in PHP 5 produces output that consists of the span tag. Both versions of PHP also wrap the output in the code tag to preserve the line breaking of the code.

Finally, both of these functions (since PHP 4.2.0) will now accept a second parameter. This is a boolean value that tells the function to either print the highlighted string out (false, which is the default) or to simply return the string (true).

Add new comment

The content of this field is kept private and will not be shown publicly.