[PHP] BBcode with color code

Hello Coders…
I realy hope you guys can help me out.
To understand PHP beter i decided to create my website from scratch without using any classes from other people. Now i have come stuck on this one little problem. After some research i found out that by using the php string “highlight_string(’<?php echo "some php code"; ?>’);” it displays the code in color (color coded) just as the tag does on this forum.

I use the following code to replace tag to bold text
[php] if(in_array(“b”,$usertags))
$done = preg_replace("#[b](.*?)[/b]#si", “\1”, $done);[/php]

My question now is how do i do this for php so it highlights the code in colorcode and is it possible to have line numbers aswell?
My 2nd question is does this also work for javascript code or other code languages?

many thx

Hi,

well analog to your ‘bold’ code you could use a ‘span’ with a class to put the enclosed text in a certain colour.
Of course you’d need to make a stylesheet with all colourclasses defined in it.
This would output :

<span class="light_red">Bladibladibla</span>

Another way to go is to include the style property inside the span. This is probably the best way to go if you use lots of different colours, user-defined per element.

<span style="color:#ff5555;">Bladibladibladibla</span>

The colour-code you can construct when echoing the line.

About the line-numbers. That may be trickier. What I would do to have line-numbers in a somewhat correct manner is to collect all output I want line-numbered in one big string, then use ‘explode()’ to split it into an array of lines and then use a ‘foreach()’ to loop through the entire array, prefixing them with a linenumber and echoing (writing to output) them.

[php]
// Collecting all lines in ‘$textblock’
$textblock = ‘’;
$textblock .= “Line number 1
\n”;
$textblock .= “Line number 2
\n”;
$textblock .= “Line number 3
\n”;
$textblock .= “Line number 4
\n”;
$textblock .= “Line number 5
\n”;

// Processing ‘$textblock’
$textblock = str_replace( “\n”, ‘’, $textblock ); // Strip newlines
if ( $textblock )
{ $textarray = explode( ‘
’, $textblock );
$count = 1; // Assuming first line is ‘1’
foreach ( $textarray as $line )
{ echo sprintf( "%04d ", $count++ ). $line. “\n”; // To get things to line nicely, use a monotyped font
}
}
[/php]
( This is of course when assuming you know beforehand when and what you want line-numbered. ) ;D

Well, anyway I hope this helps you a little,
good luck!
O.

Sponsor our Newsletter | Privacy Policy | Terms of Service