Grow your CSS skills. Land your dream job.

Highlight PHP and JavaScript Code with PHP

Published by Chris Coyier

PHP has a cool function that automatically highlights PHP code called highlight_string(); Theoretically this could be used to roll your own code highlighting on a site, rather than rely on JavaScript or some kind of external service to do it. In this article I'll show you the basics of how it works, then extended it with a few tricks. Since JavaScript is so similar to PHP in syntax, we can trick the function into highlighting JavaScript code as well. Then finally how we can bust out some smarts to auto-tab the code.

Special thanks to Benjamin Mayo (Darren Beige) who wrote the format_javascript() function we'll check out below.

Basic Usage

The highlight_string() function just accepts a string, which must begin with <?php and end with ?>. by default it echos/prints the line.

<?php highlight_string('<?php 
  $i = 1; 
  function rockOut() {
      alert("wah wah wah");
?>'); ?>

The resulting HTML is:

<pre id="code_highlighted"><code><span style="color: #0000BB">
<span style="color: #0000BB">&lt;script type="text/javascript">&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">if&nbsp;(</span><span style="color: #0000BB">true</span><span style="color: #007700">)&nbsp;{
	&nbsp;&nbsp;&nbsp;echo&nbsp;</span><span style="color: #DD0000">'The&nbsp;value&nbsp;is&nbsp;true'</span><span style="color: #007700">;
	&nbsp;&nbsp;&nbsp;echo&nbsp;</span><span style="color: #DD0000">'The&nbsp;value&nbsp;is&nbsp;false'</span><span style="color: #007700">;

</span><span style="color: #0000BB">&lt;/script&gt;</span>

Which looks like this:

Pretty wild eh? If you'd rather have that string returned rather than printed, just pass TRUE as a second parameter.

Trick it into highlighting JavaScript

Benjamin Mayo (Darren Beige) put together a PHP function that would trick PHP into highlighting JavaScript code instead of exclusively PHP. Beyond that, it also applies proper tab indentation of code, despite what is present in the file. For example, even if the original code was completely flush left like this, the output will be nicely indented.

Check out the demo to see it in action:

View Demo   Download Files

How it works

The indentation occurs by adding line breaks after every brace and semicolon if they are not already there. This puts each statement on it's own line, priming the code. However, the main bulk of the code for indentation happens in the loop itself.

$lineecho = $line;
if (substr_count($line, "\t") != $tab) {
   $lineecho = str_replace("\t", "", trim($lineecho));
   $lineecho = str_repeat("\t", $tab) . $lineecho;
$tab = $tab + substr_count($line, "{") - substr_count($line, "}");

The block works by keeping a count (in the variable $tab) of how many tab characters ("\t") there are on the previous line. The current line is counted for tabs using the substr_count() function. If the two values do not match, the echoed line is padded by the $tab value. This now means that the number of tab characters at the start of the line matches the number in the $tab variable. After this procedure, the new $tab value is calculated by taking the current $tab and adding on the number of opening braces found subtracting the number of closing braces.

The output code is in <pre> tags so the tabs display properly.


Let's say you wanted to highlight a big chunk of JavaScript code that lived in a file. Easy, just include the PHP file/function, grab the contents of that file, and run the function on it.

  $BigJavaScriptString = file_get_contents('path/to/javascript.js');
  echo format_javascript($testBigJS);

So the deal here is if you want to highlight code this way, you need to get it into a string variable. If you wanted to use this in say, a CMS, you would need to be able to save and run PHP inside the saved content areas. Or, you'd need to write some fancy regex stuff to parse content and look for particular tags and be able to extract the innards into a variable for highlighting. Above my head.

If you are interested in how you might use this to highlight other languages, check out the comment thread in the documentation, which has some attempts at highlighting XML and HTML.

Other Resources


  1. Permalink to comment#

    Wow thank you Chris nice tip

  2. Permalink to comment#

    Great tutorial….
    BTW can you tell me how is syntax highlighted code been generated for this page…

    It is a blogger page…
    Again using no JavaScript… but span tags with style attribute.
    I guess it has been generated from some tool…

    • It is built in to blogspot.

      But if it’s the different styling you want, note that format_javascript() allows you to set the colours for highlighting. This is explained in the format_javascript.php file.

    • Permalink to comment#

      I don’t think so…

    • Permalink to comment#

      Hey i think if you need no color formatting, we have no need to use format_javascript() function. If you want to highlight a JS code just use that code bwn like this
      It works well for me.
      PS – i am using this for my blog.

  3. Alex
    Permalink to comment#

    Mhh, I can’t download the file and where is the format_javascript() function? I’m blind?

    • The download link should work now.

      The format_javascript() function is inside the format_javascript.php file. Just include it in your scripts and call the function, as shown in the post.

  4. Superb. Useful function.

  5. Eddy
    Permalink to comment#

    Is there any way to add line numbers?

    • Yes.


      foreach ($data as $line) {


      foreach ($data as $num => $line) {
      $output .= ''.$num.'';

      You can change the output to whatever you like.

  6. tully
    Permalink to comment#
  7. duru
    Permalink to comment#

    Download-button not working ;-

  8. Permalink to comment#

    Why not use ? I use Pygments myself, but that’s Python not PHP.

    • Doesn’t do indentation, plus it will also be faster than that as it mainly relies on a native function.

    • Permalink to comment#

      GeShi does do indention. You probably just have to apply “white-space: pre” to it.

    • Can you show me an example?

      I examined the docs and the only mention of indentation is about how it keeps indentation intact when showing code in DIV’s.

  9. Chalk one more up for PHP!

    Benjamin – Keep up the great work, and god speed on your endeavors!

    • Thanks. I really need a dedicated tech blog.

      What does “god speed” mean?

      BTW, I love your cube scroller on your site. The day that can be done in JS willl be epic.

  10. Excelent post & tutorial.


  11. Keith
    Permalink to comment#

    Interesting. Although the markup generated is a little ugly.

    Would be interesting to see if its possible to make it use CSS classes.

  12. PHP offer two functions for highlighting PHP code: highlight_file() … when highlighting other programming code, like HTML or JavaScript.

  13. Permalink to comment#

    Nice trick, very useful. Thank you!

  14. Permalink to comment#

    This is nice, but it would be nice if you could replace the style="color: #0000BB" with something like class="identifier" or something similar.

    It looks like the blue is used for a few different things (literals, variables etc), so this approach probably wouldn’t offer the necessary granularity. Good for a quick-and-dirty though.

  15. Permalink to comment#

    For more, in php, you have also highlight_file()

  16. Permalink to comment#

    Thanks for this ; its really cool , this is the first time , i have great solution , before reading this i was color php code with css colors … so again thanks for this

  17. Permalink to comment#

    thanks for the script!

  18. Permalink to comment#

    I just knew highlight_string() function. Probably i would never knew it if i did not read your post. Thanks.

  19. thanks for this, its articel the best

  20. Excellent. Works like a charm.. Thanks!

  21. Excellent code!

    I’m a novice programmer and I just discovered highlight_string(), which got me really excited — then I discovered this, which totally rocked my world!

    Definitely going into my blog when I get around to redesigning!


This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".