khernik
khernik

Reputation: 259

Highlighting the array of code lines in PHP

I have an associative array in which every single value contains one single line of code. I display them in the foreach() loop. How can I highlight all of them?

I've found the highlight_string() function. It does work, yes, but only with PHP tags surrounding the code. The problem is that I don't want to display these tags. It's an array, so the tags should be added to every single value which would make the outcome looks ugly.

Adding tags to the beginning and the end of the array doesn't work either - I won't use highlight_string() on the whole array (surrounging foreach() loop).

And if I get rid of the PHP tags, highlighting stops working.

Is there any way to do this without including 3rd party applications?

EXAMPLE:

This is the array:

$var = array(0 => 'for($i=0;$i<5;$i++)', 1 => '// do something', 2 => '$i++', 3 => '}');

This is how I display lines of code one after another:

foreach($var as $line) 
{
   echo $line . '<br>';
}

And I want to display them as the highlighted code.

Upvotes: 0

Views: 615

Answers (2)

Dale
Dale

Reputation: 10469

This will hopefully be of assistance here:

$code_array = array(
    '<?php',
    'echo "Hello";',
    '?>'
);

echo highlight_string(implode("\r\n", $code_array), TRUE);

Addition: Since you added your code sample this will work too :)

$var = array(0 => 'for($i=0;$i<5;$i++)', 1 => '// do something', 2 => '$i++', 3 => '}');
$var = array_merge(array('<?php'), $var, array('?>'));
echo highlight_string(implode("\r\n", $var), TRUE);

Upvotes: 3

Peter Krejci
Peter Krejci

Reputation: 3192

Try to use GeSHi. It is used by many websites and open source projects.

Upvotes: 1

Related Questions