删除字符串特定部分之间的空格/换行符

I'm trying to make it so a user can add a table into their posts, the problem i'm running into, in another function i'm using nl2br to make it so it automatically add line breaks. Though, how tables work, all the line breaks will go above it causing massive amounts of space. I supplied an image below for you to be able to see what I mean. I tried using or , but I feel like i'm either using it wrong or it doesn't work in this situation.

function markupDoc($post){
    //tables
    while(($post2 = preg_replace("/\[td]((?:(?!\[td\]).)+?)\[\/td\]/s", '<td>\\1</td>', $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[tr]((?:(?!\[tr\]).)+?)\[\/tr\]/s", "<tr>\\1</tr>", $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[thead]((?:(?!\[thead\]).)+?)\[\/thead\]/s", '<thead>\\1</thead>', $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[table]((?:(?!\[table\]).)+?)\[\/table\]/s", '<table class="table table-striped table-bordered">\\1</table>', $post)) !== $post){
        $post=$post2;
    }   
    return $post;
}

String i'm submitting:

going to
[table]
    [thead]
        [td]test[/td]
        [td]test[/td]
        [td]moo[/td]
        [td]a[/td]
    [/thead]
    [tr]
        [td]test[/td]
        [td]moo[/td]
    [/tr]
    [tr]
        [td]test[/td]
        [td]test[/td]
        [td]moo[/td]
        [td]a[/td]
    [/tr]
[/table]

See the extra space

Add another function which will take care of different parts of your post. Since the part between [table] and [\table] clearly differs from the rest you should do something like:

function parsePost($post)
{
    $table_start = mb_strpos($post, '[table]');
    $table_end = mb_strpos($post, '[/table]', $table_start);
    $table_end += mb_strlen('[/table]');

    $output = nl2br(mb_substr($post, 0, $table_start));
    $output .= markupDoc(mb_substr($post, $table_start, $table_end - $table_start));
    $output .= nl2br(mb_substr($post, $table_end));
    return $output;
}

Test code: http://ideone.com/sfRn33