PHP code highlight
As you may see in this blog, all PHP codes will be highlighted so they become readable and looking good. This time I will share my script to highlight the code inside a bunch of text.
Yes, it will highlight string inside [code] and [/code] only, like following sample:
Here is a sample of PHP script:
[code]
<?php
if($name == ‘neo’){
echo ‘Hei you!’;
}
?>
[/code]
then save it as sample.php.
The result will be displayed as follow:
Here is a sample of PHP script:
if($name == 'neo'){
echo 'Hei you!';
}
?>
then save it as sample.php.
Now we see the magic behind the highlighting process:
// function to call
function highlight_code($txt){
$hasil = preg_replace_callback('{\[code\]((.|\n)+?)\[/code\]}i',"replace_code", $txt);
return $hasil;
}
// main function
function replace_code($ketemu){
$hasil = trim($ketemu[1], "\n ");
return highlight_string($hasil, true);
}
// sample of usage:
$string = "It's PHP info: [ code ] [ /code ]“;
echo highlight_code($string);
?>
The main function is the replace_code()
function that will highlight the string. But we need to return the the highlighted string back into the full strings. So we use the callback, using highlight_code() function.
Good luck ^_^