Code Highlight: The Easy Way!
Posted by James Blaha under code | highlight | function | php
June 27, 2008

This is a small function we use on this site for code highlighting. It takes content and highlights anything between [ code ] and [ /code ] tags.

<?php
function highlight_code($content) {
        
$highlighted preg_replace('/\[code\](.*?)[\/code\]/es',"'<div class=\"code\">'.highlight_string(html_entity_decode(str_replace('<br />','\n','\\1')),TRUE).'</div>'",$content);
    return 
$highlighted;
}
?>

This is a short but dense piece of code, so I'll explain it step by step, from what it does first to what it does last. First off:

str_replace('<br />','\n','\\1')

This replaces all back returns with newlines in everything between the code tags. Without this the code would be one long line.

html_entity_decode(PREVIOUS_CODE)

This decodes all html entities so they will show up correctly after being highlighted.

highlight_string(PREVIOUS_CODE,TRUE)

This does the actual code highlighting. The TRUE as the second parameter sets the function to return the code.

$highlighted preg_replace('/\[code\](.*?)\[\/code\]/es',"'<div class=\"code\">'.PREVIOUS_CODE.'</div>'",$content);

This is the hardest bit of code. It uses regular expressions to replace everything between code tags with the div. It also runs the previous functions on the section it is replacing. \\1 is a variable is the contents of the match (.*?). (.*?) matches any number of characters of any kind.

Posted by a guest on Saturday the 28th June, 2008.
yo
Posted by a guest on Saturday the 28th June, 2008.

<?php

function highlight_code($content) {

        
$highlighted preg_replace('/[code](.*?)[/code]/es',"'<div class=\"code\">'.highlight_string(html_entity_decode(str_replace('<br />','n','\1')),TRUE).'</div>'",$content);

    return 
$highlighted;

}

?>



Posted by a guest on Saturday the 28th June, 2008.
The guest must be stupid....

He didn't even include
Coder is gay too.
Posted by a guest on Saturday the 28th June, 2008.
damnit i meant to say...

the guest didn't even include "< ? PHP "

That shit is removed when I try to post.

Fuck you guys.
Posted by Manish Gupta on Monday the 30th June, 2008.
lmfao @ last guest
Posted by a guest on Sunday the 3rd August, 2008.

 Manish Smells 

Posted by a guest on Wednesday the 19th November, 2008.
7reewdx1xh46q5ws
suyzk pgpthii
http://grsbhbalfnk.com
fhijwy hyeptju
http://niolmpxxjmm.com
wfyfmb vofvoyg
http://fegilw.com
tevkiky msbp
http://vxgriyr.com
gxiia ngal
http://jeswbjwxk.com
kdwpj nizkqkab
http://lpxhwjbotx.com
yobmc vuxglsll
http://vjbsrvkm.com
ylgruc iaihne
http://qxhzsi.com
vwjozm ydmdx
http://krtqfimgi.com
zjesrq ttzyqzb
http://gngzyhlcl.com