Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Mar 3, 2010

Highlight code with php

if you write any programming related article or blog post, you must need some code highlighter plug-ins etc.  In this post I’ll show you the way we can highlight code in a colorful format, with basic php functions, without rely on JavaScript or some kind of external service.
Basic Usage
PHP has a powerful function that highlights PHP code called highlight_string();.The highlight_string() function accepts a string, which must begin with <?php and end with ?>. by default it prints the line.

<?php highlight_string('<?php

  $i = 1; 

  function poo() {

      echo "i am poo";

  }

?>'); ?>

The resulting HTML is:

<span style="color: rgb(0, 0, 0);">

<span style="color: rgb(0, 0, 187);">&lt;?php&nbsp;highlight_string</span><span style="color: rgb(0, 119, 0);">(</span><span style="color: rgb(221, 0, 0);">'&lt;?php

<br>&nbsp;&nbsp;$i&nbsp;=&nbsp;1;&nbsp;

<br>&nbsp;&nbsp;function&nbsp;poo()&nbsp;{

<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"i&nbsp;am&nbsp;poo";

<br>&nbsp;&nbsp;}

<br>?&gt;'</span><span style="color: rgb(0, 119, 0);">);&nbsp;</span><span style="color: rgb(0, 0, 187);">?&gt;</span>

</span
Sounds useful naah?.
If you want to return the result rather than printing, just pass TRUE as a second parameter.

Trick it into highlighting other language code

This function can be used to highlight other language codes too, because the condition is code must begin with <?php and end with ?>. We can use this function to highlight our JavaScript code too, Since JavaScript is so similar to PHP in syntax, as well as for HTML or CSS.
Here is the function that will do this for you -

 function highlightCode($code){
   $highlighted highlight_string('<?php '.$code.' ?>',TRUE); 
   return str_replace('&lt;?php','',str_replace('?&gt;','',$highlighted));

} 

Demo

Here is no need to link; see all the code highlighted here on this blog is with this method.

Labels:




By :