User:Marksw/PHPHighlight

Blue Glass Arrow.svg MediaWiki-2020-logo.svg
This page should be moved to MediaWiki.org.
Please do not move the page by hand. It will be imported by a MediaWiki.org administrator with the full edit history. In the meantime, you may continue to edit the page as normal.

PHPHighlight is a PHP syntax highlighting extension for MediaWiki

SyntaxEdit

<php>php code</php>


ExampleEdit

<php>
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
</php>

ResultEdit

This will give something like the following (though not exactly):


// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo
$pieces[0]; // piece1
echo $pieces[1]; // piece2


SourceEdit

<?php
/*
** PHPHighlight.php
** PHP syntax highlighting MediaWiki Extension
**
** Version 1.0 by Mark Sweeting 2005/09/05
**     http://meta.wikimedia.org/wiki/User:Marksw/PHPHighlight
*/

$wgExtensionFunctions[] = "wfPHPHighlightExtension";

function wfPHPHighlightExtension() {
   global $wgParser;
   $wgParser->setHook( "php", "renderPHP" );
}

function renderPHP( $input="", $argv=array() )
{
   // need to add the PHP tags so that the highlight_string()
   // method works.
   $input = '<?php' . $input .  '?>' . "\n";
   $output = highlight_string($input, true);
   // now remove the outer PHP tags
   $output = str_replace (array('<?php',
                                '?>',
                                '<code>',
                                '</code>'),
                          '',
                          $output);

   return '<pre>' . preg_replace('|<br ?/?>|i', "\n", trim($output)) . '</pre>';
}
?>

Installing the extensionEdit

Copy the code above into a file called PHPHighlight.php and save this into your wiki extensions directory.

Then add the following line to the end of your LocalSettings.php file:

include("extensions/PHPHighlight.php");

and you are ready to go.

Related extensionsEdit

If you would like a syntax highlighter for many other languages (including PHP) then see GeSHiHighlight