by craig campbell

Nijikodo is an object oriented code syntax highlighting library written in PHP.
Current supported languages include CSS, HTML, JavaScript, and PHP. The generic regex patterns work for other languages as well.



php 5.3


to install put the lib directory somewhere in your include path:

require 'lib/Nijikodo/Parser.php'; // you can optionally set a css class prefix (defaults to 'niji_') Nijikodo\Parser::setCssPrefix('code_');

to syntax highlight code from a form field:

$text = $_POST['text']; $text = Nijikodo\Parser::process($text);

use these special tags in the form field to specify that this block of text is code:

{code:language|height:200} // this is where the code goes {code}

this can also be done directly in a view using output buffering like so:

<!-- begin capturing code --> <?php Nijikodo\Parser::captureStart(); ?>
{code:javascript} // code goes here {code}
<!-- output what has been captured --> <?php echo Nijikodo\Parser::output(); ?>

additionally if you have a string that you already know is a specific type of code you can do this:

$string = '<p>this is my string</p>'; $html_string = Nijikodo\Parser::toHtml($string, 'html');

finally if you would like to run your string through some other functions you can tokenize the code blocks and fill them back in later

$text = $_POST['text']; $text = Nijikodo\Parser::tokenizeCodeBlocks($text); $text = nl2br($text); $text = Nijikodo\Parser::replaceTokens($text);



// this is some sample php code $i = 0; for ($i = 0; $i < 25; ++$i) { echo $i; } function customFunction() { return mt_rand(1, 100); } $fruits = array('banana', 'strawberry', 'blueberry', 'apple', 'blackberry'); asort($fruits); foreach ($fruits as $key => $value) { echo $value; }


// open external links in a new window using jquery $(document).ready(function() { $("a[rel='external']").live("click", function() { $(this).attr("target", "_blank"); }); });


<!-- html with php inside of it! --> <ul class="user_list"> <?php foreach ($this->users as $user): ?> <li><a href="<?php echo $user->getUrl(); ?>"><?php echo $user->getName(); ?></a></li> <?php endforeach; ?> </ul>


/* css used for this demo */ .niji_code { font-family: 'monaco', courier, monospace; font-size: 11.5px; overflow: auto; margin-top: 10px; margin-bottom: 10px; padding: 10px; background: #03050A; color: #fff; -moz-border-radius: 5px; -webkit-border-radius: 5px; white-space: pre-wrap; } .niji_html { color: #7F90AA; } .niji_keyword, .niji_define { color: #FBDE2D; } .niji_int { color: #D8FA3C; } .niji_comment { color: #E40700; } .niji_class, .niji_function { color: #8DA6CE; } .niji_string { color: #61CE3C; } .niji_default { color: #fff; } .niji_tag { color: #7F90AA; } .niji_method { color: #FF6400; }