Highlight Code In PHP

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:

highlight_string('<?php 
function checkslash($slashes_string){
  if (get_magic_quotes_gpc()==1) {
    return $slashes_string;
  }else{
    return addslashes($slashes_string);
  };
};
?>');

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.
CAPTCHA
9 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.