How to make simple syntax hightlighter in PHP

PHP SyntaxhighlighterIn the following article I will show you how you can write your own syntax highlighter with a few lines of PHP. By use of the following PHP snippet you can easily display PHP code on your homepage.

The whole thing is much more easily than you think. Most of the work is done by an internal PHP function named highlight_file. This function reads a file and formats the source code in color. We then merely have to count the lines of the file and output the line numbers, as well as preformat the font.

Since the snippet is not that long, I think the comments in the snippet itself are sufficient. If you still have any questions, just write a comment.

<?php
function highlight_sourcecode($file)
{
	//Count the lines of the input file
	$amount_of_lines = count(file($file));

	//Create a list with all line numbers
	$list_linenumbers = range(1, $amount_of_lines);

	//Format line numbers as string and add a
	//line break after each line (<br />)
	$lines = implode($list_of_linenumbers, '<br />');

	//Read source code and format it
	//'true' gives the formatted code as return value
	//'false' would echo the formatted source code
	$sourcecode = highlight_file($file, true);

	//HTML output. CSS code to format the table
	echo '
	<html>
		<head>
			<style type="text/css">
				.codewrapper {
				margin: 5px;
				border: 1px dashed dimgray;}

				.id {
				text-align: right;
				color: dimgray;
				font: 10pt 'Courier New';
				padding-right: 5px;
				border-right: 1px dashed dimgray;}

				.code {
				padding-left: 5px;}
			</style>
		</head>

		<body>
			<table class="codewrapper">
				<tr>
					<td class="id">'.$lines.'</td>
					<td class="code">'.$sourcecode.'</td>
				</tr>
			</table>
		</body>
	</html>';
}

//Call the display function
highlight_sourcecode("short.php");
?>

I saved the snippet in a file called short.php. In the snippet it calls itself and thus gives out its own source code. You can watch a demo here.

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked