<?php

function parse($str) {
    return preg_replace_callback('@\[(\w+)(?:="(?>.*?"))?(?: \w+="(?>.*?"))*](?:(.*?)\[/\1])?@s',
        function($matches) { return $matches[2] ? parse($matches[2]) : ''; },
        $str
    );
}

$test_case =
'[b]Test 1[/b]
[b][i]Test 2: nested BBCodes and multiple occurrences of the same one[/i][/b]
[img src="http://e...content-available-to-author-only...e.com/image.png"]
[sup][i]A pretty bird.[/i][/sup]
[p id="malformed]Lorem ipsum[/p] (the end tag also shouldn\'t be removed)
[url="example.com" target="_blank"]New window[/url]
[quote="The other demo"][b]This is in bold.[/b]
[url="http://w...content-available-to-author-only...e.com/"]Link[/url]
[img src="http://w...content-available-to-author-only...e.com/image.png" width="100" height="100"]

[color=red]Darn, no red.[/color ]
[img src="http://w...content-available-to-author-only...e.com/image.png width="100" height="100"]
[sup]^ malformed tag, shouldn\'t match[/sup][/quote]
[p class="note"]Not all of the lines above will match in the same way.[/p]';

echo nl2br(parse($test_case));

?>