Page 1 of 1

PHP color coder (like on phpdn and php.net

Posted: Thu Nov 15, 2007 10:19 am
by Jonah Bron
Hi,

I am working on a php color coder for my blog. Like on phpdn and php.net. This is what I have so far, but if the word "if" or "echo" or anything like that comes up inside quotes, it is still colored. Same with comments (forward slashes (//)).

The only problem left, is how to get it to stop applying the coloration to words inside quotes.

Code: Select all

<?php
//apply specified color function
function color($col,$con){
return '<span style="color:#'.$col.';">'.$con.'</span>';
}
//php code
$php = "<?php
if ($x=='qwerty'){
echo 'billy bob';
}
//comment line
echo 'string //comment';
print 'bob';
?>";

$php = explode('
',$php);
$count = count($php);
$x = 0;

while ($x<$count){
$php[$x] = str_replace('//','<span style="color:#888;">//',$php[$x]);
if (eregi('<span style="color:#888;">//',$php[$x])){
$php[$x] .= '</span>';
}else{
$php[$x] = str_replace('<?php',color('0a0','<?php').'<span style="color:00f;">',$php[$x]);
$php[$x] = str_replace('?>','</span>'.color('0a0','?>'),$php[$x]);
$php[$x] = str_replace('if',color('0f0','if'),$php[$x]);
$php[$x] = str_replace('else','<span style="color:#0f0;">else</span>',$php[$x]);
$php[$x] = str_replace('elseif','<span style="color:#0f0;">elseif</span>',$php[$x]);
$php[$x] = str_replace('echo',color('0f0','echo'),$php[$x]);
$php[$x] = str_replace('return',color('0f0','return'),$php[$x]);
$php[$x] = str_replace('print',color('0f0','print'),$php[$x]);
}
$x += 1;
}
$php = implode('<br />
',$php);

echo $php;
?>

Posted: Thu Nov 15, 2007 10:42 am
by s.dot

Posted: Thu Nov 15, 2007 10:48 am
by Jonah Bron
Ha ha. Like my dad says: K.I.S (keep it simple, with out the stupid :wink: ). Didn't know about that function. Thanks :D



B.T.W. Congrats on your mod status

Posted: Thu Nov 15, 2007 10:49 am
by s.dot
Thank you! :)

Posted: Thu Nov 15, 2007 10:05 pm
by sunilbhatia79
You can also use this library:
http://qbnz.com/highlighter/

Posted: Thu Nov 15, 2007 10:23 pm
by RobertGonzalez
GeSHi, the library mentioned in the post above, is a fairly heavy library. It offers a lot of cool features, but if all you are looking for is syntax highlighting of PHP code, use the built-ins scottayy mentioned.

Just make sure when using those functions that the code you are highlighting opens with <?php and not <? or it may not highlight.

Posted: Fri Nov 16, 2007 9:19 am
by Jonah Bron
Okay, thanks, everyone!

Posted: Fri Nov 16, 2007 9:20 am
by Jonah Bron
yes, color coding syntax is all I was looking for. Thanks, everyone!