Search code examples
phphtmlregexparsingbbcode

PHP Formatting Regex - BBCode


To be honest, I suck at regex so much, I would use RegexBuddy, but I'm working on my Mac and sometimes it doesn't help much (for me).

Well, for what I need to do is a function in php

function replaceTags($n)
{
    $n = str_replace("[[", "<b>", $n);
    $n = str_replace("]]", "</b>", $n);
}

Although this is a bad example in case someone didn't close the tag by using ]] or [[, anyway, could you help with regex of:

[[ ]] = Bold format

** ** = Italic format

(( )) = h2 heading

Those are all I need, thanks :)

P.S - Is there any software like RegexBuddy available for Mac (Snow Leopard)?


Solution

  • function replaceTags($n)
    {
        $n = preg_replace("/\[\[(.*?)\]\]/", "<strong>$1</strong>", $n);
        $n = preg_replace("/\*\*(.*?)\*\*/", "<em>$1</em>", $n);
        $n = preg_replace("/\(\((.*?)\)\)/", "<h2>$1</h2>", $n);
        return $n;
    }
    

    I should probably provide a little explanation: Each special character is preceded by a backslash so it's not treated as regex instructions ("[", "(", etc.). The "(.*?)" captures all characters between your delimiters ("[[" and "]]", etc.). What's captured is then output in the replacements string in place of "$1".