Networking, Programming and Graphics - Tutorials
ONLINEHOWTO.net Tutorials Category

Coloring PHP code output in text

Type: Code Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Level: Beginner Networking, Programming and Graphics - Tutorials 
Networking, Programming and Graphics - Tutorials
Date: 2009-Oct-14
Networking, Programming and Graphics - Tutorials
Visited: 647 times
Networking, Programming and Graphics - Tutorials
Rating: Networking, Programming and Graphics - Tutorials
Networking, Programming and Graphics - Tutorials
Published: Tony Potter

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:
<?php
$link = mysql_connect('db_host', 'db_username', 'db_password');
if (!$link) 
{
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
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.
<?php
$a="<?php
$link = mysql_connect('db_host', 'db_username', 'db_password');
if (!$link) 
{
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>";
highlight_string($a);
?>
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:
<?php
$link 
mysql_connect('db_host''db_username''db_password');
if (!
$link
{
    die(
'Could not connect: ' mysql_error());
}
echo 
'Connected successfully';
mysql_close($link);
?>
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.
Rate this tutorial:                    
Post Comment

Need a specific tutorial? Do not hesitate and submit a request!
Your e-mail: