phpregexpreg-replacetext-parsingbbcode

"Compilation failed: unmatched parentheses" error while parsing BBCode text with regex


I get an error saying "Compilation failed: unmatched parentheses at offset 11" while trying to parse BBCode with an array of regex patterns.

I have no idea what offset 11 means and I've checked all my parentheses and there are no unclosed sets.

Here's my code:

function bbParse($string) {
    $codes = array(
        '/\[b\](.+?)\[\/b\]/' => '<b>$1</b>', 
        '/\[h2\](.+?)\[\/h2\]/' => '<h2>$1</h2>', 
        '/\[h3\](.+?)\[\/h3\]/' => '<h3>$1</h3>', 
        '/\[p\](.+?)\[\/p\]/' => '<p>$1</p>', 
        '/\[quote\](.+?)\[\/quote\]/' => '<blockquote>$1</blockquote>', 
        '/\[img\](.+?)\[\/img\]/' => '<img src=\'$1\' alt=\'Image Not Available\'>',
        '/\[url=\(.+?)\](.+?)\[\/url\]/' => '<a href=\'$1\'>$2</a>'
    );
    
        
    $string = preg_replace(array_keys($codes), array_values($codes), $string);

    return $string;
}

Solution

  • /\[url=\(.+?)\](.+?)\[\/url\]/

    The first grouping paren in this regex is escaped, making it a literal parenthesis character. The closing one therefore has no matching opening paren. You need to remove the \ preceding the first parenthesis, making it thus:

    /\[url=(.+?)\](.+?)\[\/url\]/