PHP syntax highlighter

Here’s a basic PHP “syntax highlighter” function:


function highlight($string)
{
	$syntax = array(
		array('/([|\"|\'].*[|\"|\'])([^A-Za-z0-9\s])/Us', '<span style="color:#808080;">$1</span>$2'), //Strings
		array('/(\[|\s)([0-9]{1,})(\]|\s)/', '$1<span style="color:#FF8000;">$2</span>$3'), //Numbers
		array('/(\$[a-zA-Z0-9_]+)/', '<span style="color:#000080;">$1</span>'), //Variables
		array('/(\/\*)(.*)(\*\/)/s', '<span style="color:#008000;">$0</span>'), //Multi-line comment
		array('/(\/\/)(.*)(\n)/', '<span style="color:#008000;">$1$2</span>'), //Single line comment
		array('/[\[|\]]/', '<span style="color:#8000FF;">$0</span>'), //Slashes
		array('/[\(|\)]/', '<span style="color:#8000FF;">$0</span>'), //Brackets
		array('/[\[|\]]/', '<span style="color:#8000FF;">$0</span>'), //Square brackets
		array('/[\{|\}]/', '<span style="color:#8000FF;">$0</span>'), //Curly braces
		array('/[\,|\.|\?|\!]/', '<span style="color:#8000FF;">$0</span>'), //Punctuation
		array('/[\£|\^|\&|\-|\+|\%|\@|\~|\`|\¬]/', '<span style="color:#8000FF;">$0</span>'), //Miscellaneous
		array('/\b(?<!\$)(as|break|case|class|const|continue|declare|default|do|echo|else|elseif|endfor|endforeach|endif|endswitch|endwhile|extends|false|for|foreach|function|global|if|include|include_once|interface|namespace|new|null|print|private|protected|public|require|require_once|return|self|switch|throw|true|use|var|while)\b/', '<span style="color:#0000FF; font-weight:bold;">$1</span>') //Key words
	);

	foreach($syntax as $set){
		$string = preg_replace($set[0], $set[1], $string);
	}

	return "<pre>$string</pre>";
}

This is a somewhat rudimentary script, in that it’s not very flexible- I wrote it only with PHP in mind (although it could be easily extended for other languages)- and nor is it very robust. I wrote this as simply as possible, as an exercise in regex patterns more than anything- so it’s not going to be rivaling GeSHi!

In the future when I have an actual need for it, I’ll make modifications and improvements; or more likely, rewrite it from scratch. However, you may find it useful in some way, which is why it’s here.

This entry was posted in PHP and web. Bookmark the permalink.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>