Jump to content

PHP Syntax Highlighter


scheols

Recommended Posts

I find it easier to use a function called [url=http://uk.php.net/manual/en/function.preg-replace-callback.php]preg_replace_callback[/url] when doing PHP BBCode parsers. Heres a quick demo:
[code]<?php

function bbcode($txt)
{
    // bbcodes
    $bbcodes = array( "|\[b\](.+)\[/b\]|is",
                      "|\[u\](.+)\[/u\]|is",
                      "|\[i\](.+)\[/i\]|is"
                    );

    // html
    $replace = array( "<strong>$1</strong>",
                      "<u>$1</u>",
                      "<em>$1</em>"
                    );

    $text = preg_replace($bbcodes, $replace, $txt);

    // call a dedicated function to parse our PHP BBCodes:
    $text = preg_replace_callback("#\[php\](.*?)\[\/php\]#is", 'doPHP', $text);

    return nl2br($text);

}

// our dedicated PHP BBCode function
function doPHP($matches)
{
    #echo '<pre>' . print_r($matches, true) . '</pre>';

    //highlight PHP Code
    $php = highlight_string($matches[0], true);

    // remove the mataches
    unset($mataches);

    // remove the php BBCodes
    $php = preg_replace("#(\[php\]|\[/php\])#i", "", $php);

    //clean up spaces and extra line breaks
    $php = str_replace('&nbsp;&nbsp;', '&nbsp; ', $php);
    $php = str_replace('<br />', '', $php);

    return $php;
}

$str = "[code=php:0]<?php
echo 'hello world';

if(\$var == 'hello world')
{
    echo 'true';
}
?>[/code]";

// call the bbcode parser function.
$str = bbcode($str);

echo $str;

?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.