Search code examples
phpregextext-parsingbbcode

Dot not matching text with newlines while trying to parse BBCode with regex


I am using a little BBCode parsing function for a forum I have.

It works well when the text between two b tags has no newlines in it.

[b]Text[/b]

it will print Text in bold.

However, if the inner text contains a newline, it doesn't replace properly.

[b]
Text[/b]

My function:

function BBCode ($string) {
    $search = array(
        '#\[b\](.*?)\[/b\]#',
    );
    $replace = array(
        '<b>\\1</b>',
    );
    return preg_replace($search , $replace, $string);
}

Then when echo'ing it:

echo nl2br(stripslashes(BBCode($arr_thread_row[main_content])));

Sample text:

[b]    

Text

[/b]

Should become:

<b>

Text

</b>

Solution

  • You need the multiline modifier, which makes your pattern something like #\[b\](.*?)\[/b\]#ms

    (note the trailing m)