Coloring PHP code output in text

The subject of this tutorial will be how PHP code can be colored when you publish it within page text.
We have had inquires about how we are coloring the PHP code on our pages, so we decided to create a simple tutorial.

There are many ways to, but the one that will work on almost all platforms will be to use the built in option inside PHP.

The option is called ‘highlight_strin()’ and has syntax like:

highlight_string ( string $str [, bool $return = false / true ] )

"It returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP."

It can be used as for $str you will put the PHP code that you want colored, and for the optional $return you can put ”true” or ”false”, or as we are going to do in our example, to leave it unused.

Let’s take for example a simple MySQL connection test script:

If you are wondering why it is not in code field is because I want to exalt the final effect.

Now let’s see how the coloring can be done.

As I explained above the string should be as a first option inside the PHP function ‘highlight_strin()’. The problem is that the function brackets will be torn and this may lead to syntax errors.
So as it is always better to be done with variable ‘$a’ to appropriate the above code and then to color it with the function.

So in our example the colored PHP code output listing will become:

Using variable to color PHP codes has another benefit, exactly if you are using a form with POST or GET to enter scripts on your website.

If you want to see other PHP tutorials you can use the search field on the site or to visit the PHP for beginners article.

Filed Under: PHP

Anthony Gee About the Author: Anthony G. is an IT specialist with more than 9 years of solid working experience in the Web Hosting industry. Currently works as server support administrator, involved in consultative discussions about Web Hosting and server administration. One of the first writers in the Onlinehowto.net website, now writing for Free Tutorials community - he is publishing tutorials and articles for the wide public, as well as specific technical solutions.

Leave a Reply