0

So I have a tag like [code style=php]<?php echo "Hello world!"; ?>[/code]

A user may use plenty of those tags in a textarea so what I want to search for is [code style=(.*)]text[/code] so if the style is PHP for example I want to do highlight the code inside the tags and so on with other languages.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
stergosz
  • 5,754
  • 13
  • 62
  • 133

1 Answers1

0

Why reinvent the wheel. Stackoverflow already has answer for this: PHP syntax highlighting

UPDATE

After reading comment. You can convert it like this:

<?php
function parseContent( $string )
{
    $search = '/\[code style="(.*?)"\](.*?)\[\/code\]/is';
    preg_match_all($search, $string, $output);

    foreach( $output[ 0 ] as $idx => $raw_html)
    {
        $style   = $output[ 1 ][ $idx ];
        $content = $output[ 2 ][ $idx ];

        $new_html = "<div class='codetext' id='$style'>$content</div>";
        $string = str_replace($raw_html, $new_html, $string);
    }

    return $string;
}
?>

Here's some test code:

<?php
$string = <<<EOM
some pre content
[code style="php"]
<?php
    echo "this is PHP";
?>
[/code]
some content in the middle
[code style="html"]
<body>
    <h1>TITLE IS HERE!</h1>
</body>
[/code]
another content after content
EOM;

$string = parseContent( $string );
?>
Community
  • 1
  • 1
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
  • as i see there is a javascript highlighter, but what i trully want is to make it inside in PHP, because the users use [code style=php]php code[/code] or c,java,c++ and so on this then gets replaced with a preg_replace function to div so it will create the CODE container and put inside the code text... the problem is how i will check for each code tag inside an article and replace each code tag with the proper highlight colors... – stergosz Apr 14 '11 at 09:00
  • Im using this for now: $search = array( '/\[code style=(.*?)\](.*?)\[\/code\]/is' ); $replace = array( '
    $2
    ' ); return preg_replace($search,$replace,$input); so if style = php and inside the code tags i have it will output
    how can i check what $1 is in order to highlight the $2 properly ?
    – stergosz Apr 14 '11 at 09:46