-
Feb 19, 2008
PHP Source Highlighting
I wanted to customize the PHP highlight_string function so I could change the colors to fit this site. I figured I would share it with anyone who wanted to see it.
<?php /*
@sources = code to highlight;
@classes = boolean for using classes instead of inline styles
*/
function php_highlight($source, $classes = false)
{
if (version_compare( phpversion(), "5.0.0", "<")) return "PHP 5 required";
$r1 = $r2 = '##';
if ( strpos($source,' ?>') === false )
{
$source = "<?php ".$source." ?>";
$r1 = '#<?.*?(php)?.*? #s';
$r2 = '#?>#s';
}
elseif (strpos($source,'<? ') !== false)
{
$r1 = '--';
$source = str_replace('<? ','<?php ',$source);
}
$source = str_replace("&", "&", $source);
$source = highlight_string($source,true);
if ($r1 =='--') $source = preg_replace('#(<?.*?)(php)?(.*? )#s','\1\3',$source);
$source = preg_replace (array ( '/.*<code>s*<span style="color: #000000">/',
'#</span>s*</code>#', // <code><span black>
$r1, $r2, // php tags
'/<span[^>]*></span>/' //empty spans
),'',$source);
/*
If you want to use classes in your spans instead of the default colors
Replace style= with class=
*/
if ($classes)
$source = str_replace( array('style="color: #0000BB"','style="color: #007700"','style="color: #DD0000"','style="color: #FF8000"'),
array('class="phpdefault"','class="phpkeyword"', 'class="phpstring"','class="phpcomment"',),$source);
return $source; ?>and then to use this code I simply searched through the content of a post like this:
<?php
if(strpos('[php]', $content) !== TRUE) {
$regex = '/\[php\](.*?)\[\/php\]/ise';
preg_match_all($regex, $content, $matches);
for($i = 0; $i < count($matches); $i++) {
$phpcode = php_highlight($matches[1][$i], true);
$content = str_replace($matches[0][$i], "<?php".$phpcode."?>", $content);
}
} ?>Class names to customize color:
phpdefault, phpkeyword, phpstring, phpcommentPosted by Mark on 02/19/2008 2:02 PM in PHP Tutorials
Comments
haveboard
02/19/2008
'PHP highlight_string function' == 'PWNED'