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
https://forums.phpfreaks.com/topic/16173-php-syntax-highlighter/#findComment-66921
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.