and like us on FB

This article is as a reference to a few others we have scheduled over the next couple of weeks. Simply because we didn’t want to repeat ourselves, we’ve published this introduction to PHP’s highlight_file() (and highlight_string() ) functions. It comes primarily as a precursor to an article called “Syntax Highlighting in WordPress“.

Rendering code with appropriate syntax is a big part of what we share on this website. Despite the fact we use the brilliant Crayon Syntax Highlighter for formatting code, we often have revert to in-house alternatives to service particular requirements. It’s these needs that are addressed in our upcoming posts.

PHP’s highlight_file() Function

PHP’s highlight_file() will “print out or return a syntax highlighted version of the code contained in [a file] using the colors defined in the built-in syntax highlighter for PHP”.

Consider this function:

<?php
function beliefmedia_hello_world() {
  return 'Hello World!';
}
?>

To use the highlight_file() you should reference the local text (or other) file containing the code via its full path. You must include the opening PHP tags.

highlight_file('/home/public_html/dir/phpText.txt');

The function will return this:

PHP’s Syntax highlight_file() Function with Line Numbers and Alternating Coloured Rows

To return the code rather than print it directly to your screen, the second parameter ($return) should be set to true. For example:

echo highlight_file('/home/public_html/dir/php-code.txt', true);

Adding Line Numbers and Alternating Coloured Rows

The highlighted code that is returned by default using highlight_file()is rather bland and boring. Adding line numbers and alternating colored rows makes it look a little more respectable. The result of the function below will return highlighted code that looks like this:

PHP’s Syntax highlight_file() Function with Line Numbers and Alternating Coloured Rows

The PHP Function

The following function will return code syntax highlighted code with line numbering.

1
<?php
2
/*
3
    PHP's Syntax highlight_file() Function with Line Numbers and Alternating Coloured Rows
4
    http://www.beliefmedia.com/php-syntax-highlighter
5
    http://php.net/manual/en/function.highlight-file.php
6
*/
7
 
8
function beliefmedia_highlight_file($file) {
9
 
10
  $code = substr(highlight_file($file, true), 36, -15);
11
  $lines = explode('<br />', $code);
12
  $lines = array_combine(range(1, count($lines)), $lines);
13
 
14
  $line_count = count($lines);
15
  $pad_length = strlen($line_count);
16
        
17
  $return .= '<div style="width: 100%; display: inline-block; display: flex;"><code>';
18
   foreach($lines as $i => $line) {
19
     $lineNumber = str_pad($i + 1,  $pad_length, '0', STR_PAD_LEFT);
20
       if ($i % 2 == 0) {
21
         $numbgcolor = '#C8E1FA';
22
         $linebgcolor = '#F7F7F7';
23
         $fontcolor = '#3F85CA';
24
          } else {
25
         $numbgcolor = '#DFEFFF';
26
         $linebgcolor = '#FDFDFD';
27
         $fontcolor = '#5499DE';
28
       }
29
 
30
     if ($line == '') $line = '&nbsp;';
31
     $return .= '<div style="background-color: ' . $numbgcolor . '; white-space: nowrap; width: 23px; float: left; padding: 0px 2px 0px 2px; text-align: center; color: ' . $fontcolor . ';">' . $i . '</div><div style="background-color: ' . $linebgcolor . '; margin-left: 0; float: left; padding-left: 5px; width: calc(100% - 32px);">' . $line . '</div>';
32
   }
33
  $return .= '</code></div>';
34
 
35
 return $return;
36
}
37
 
38
/* Usage */
39
echo beliefmedia_highlight_file('text-file.txt');

The above function is rendered using our sample WordPress PHP Syntax Highlighting function. It is designed with only CSS, and is intended to emulate the look and feel of Crayon’s default skin. The article will be found here when published.

Altering Syntax Color and Font Weight

The syntax color and font weight can be altered by way of altering php_ini() configuration options. Add the following code at the beginning of your function or into your custom-fuctions.php file.

You’ll obviously want to alter the #000000 color.

PHP’s highlight_string() Function

PHP’s highlight_string() function works in much the same way as the highlight_file() function with the exception that, as the function implies, will highlight a string. As with the former function, you can store the result into variable with the second argument of true.

Security

The highlight_file() function will read an entire page indiscriminately meaning that you might inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

WordPress Shortcode

We’ve provided shortcode for no other reason than demonstration purposes. Our forthcoming post introduces a much more usable solution.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

The shortcode requires the beliefmedia_highlight_file() function. When used on a simple ‘Hello World’ text file, the following will be rendered:

1
<?php
2
/*
3
    PHP's Syntax highlight_file() Shortcode
4
    http://www.beliefmedia.com/php-syntax-highlighter
5
*/
6
 
7
echo "Hello World!";
8
?>

Shortcode used was [simplephp file="hello-world.txt"].

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Applications

Our scheduled function supports rendering of PHP code that is provided by various code repositories. For example, as shown in the below image, the Snipplr default embed code is awful. While the attribution text isn’t entirely inappropriate, the default H3 tags are what bothered me most.

PHP’s Syntax highlight_file() Function with Line Numbers and Alternating Coloured Rows

Pictured: Snipplr code embeds are awful.

Our upcoming Snipplr embed code will look as follows (using a variation of the function above).

1
<?php
2
function getYoutubeVideoID($sVideoURL) {
3
    $sVideoID = preg_replace('%.*(v=|/v/)(.+?)(/|&|\\?).*%', '$2', $sVideoURL);
4
    return $sVideoID;
5
}

Until we add additional languages it will only work on PHP.

Considerations

  • Both functions described above will return just the formatted HTML required to sketch the code. For this reason, there’s no linewrap. Our WordPress function addresses this.
  • Using file_get_contents() will return a file into a string, which may then be used with highlight_string() as opposed to highlight_file().
  • Your PHP string or file must include the opening tag. To check, consider using the following before you apply the syntax highlight function:

  • While we’ve used Snipplr as our embed example, the code could essentially be applied to any repository. Code is cached locally to avoid repeated requests to either the API or remote service.

Download

Title: PHP's Syntax Highlighting
Description: PHP's Syntax highlight_file() Function with Line Numbers and Alternating Coloured Rows.
Download: Shortcode (V0.2) | WP Plugin (V0.2) | PHP Code (V0.2)

Shortt URL for this post: http://shor.tt/1PY6