Search code examples
phpsyntax-highlightingmarkdownpreg-replace-callbackgeshi

Geshi with Markdown


Im trying to get GeSHi to work with markdown.

A simple use for Geshi is as follows:

$geshi = new GeSHi($message, 'c');
print $geshi->parse_code();

The above code takes in the whole of message and turns it into Highlighted code

I also have my Markdown Function

print Markdown($message);

I was trying to use call back function to preg_match the <pre> tags returned from markdown and run the geshi->parse_code(); function on the returned values

Here is my code

print preg_replace_callback(
   '/<pre.*?>(.*?[<pre.*?>.*<\/pre>]*)<\/pre>/gism',
    create_function(
        // single quotes are essential here,
        // or alternative escape all $ as \$
        '$matches',
        '$geshi = new GeSHi($matches[0], \'php\'); return $geshi->parse_code()'
    ),
    Markdown($blog_res['message']));

Am i on the right track?

Is My Regex right? it works on http://gskinner.com/RegExr/

Thanks for the help


Solution

  • it was the regex :(

    instead of

    /<pre.*?>(.*?[<pre.*?>.*<\/pre>]*)<\/pre>/gism 
    

    use (remove the global flag)

    /<pre.*?>(.*?[<pre.*?>.*<\/pre>]*)<\/pre>/ism 
    

    But if you are using markdown, you have to remember to compensate for the code blocks that are on thier own therefore you need to replace only the ones that are in the format of <pre><code>...MyCode</code></pre> and leave out Hello <code>MyCode</code> Therefore you need the following

    '/<pre.*?><code.*?>(.*?[<pre.*?><code.*?>.*<\/code><\/pre>]*)<\/code><\/pre>/ism',