fork download
  1. <?php
  2.  
  3. function parse($str) {
  4. return preg_replace_callback('@\[(\w+)(?:="(?>.*?"))?(?: \w+="(?>.*?"))*](?:(.*?)\[/\1])?@s',
  5. function($matches) { return $matches[2] ? parse($matches[2]) : ''; },
  6. $str
  7. );
  8. }
  9.  
  10. $test_case =
  11. '[b]Test 1[/b]
  12. [b][i]Test 2: nested BBCodes and multiple occurrences of the same one[/i][/b]
  13. [img src="http://e...content-available-to-author-only...e.com/image.png"]
  14. [sup][i]A pretty bird.[/i][/sup]
  15. [p id="malformed]Lorem ipsum[/p] (the end tag also shouldn\'t be removed)
  16. [url="example.com" target="_blank"]New window[/url]
  17. [quote="The other demo"][b]This is in bold.[/b]
  18. [url="http://w...content-available-to-author-only...e.com/"]Link[/url]
  19. [img src="http://w...content-available-to-author-only...e.com/image.png" width="100" height="100"]
  20.  
  21. [color=red]Darn, no red.[/color ]
  22. [img src="http://w...content-available-to-author-only...e.com/image.png width="100" height="100"]
  23. [sup]^ malformed tag, shouldn\'t match[/sup][/quote]
  24. [p class="note"]Not all of the lines above will match in the same way.[/p]';
  25.  
  26. echo nl2br(parse($test_case));
  27.  
  28. ?>
Success #stdin #stdout #stderr 0.01s 52488KB
stdin
Standard input is empty
stdout
Test 1<br />
Test 2: nested BBCodes and multiple occurrences of the same one<br />
<br />
A pretty bird.<br />
[p id="malformed]Lorem ipsum[/p] (the end tag also shouldn't be removed)<br />
New window<br />
This is in bold.<br />
Link<br />
<br />
<br />
[color=red]Darn, no red.[/color ]<br />
[img src="http://w...content-available-to-author-only...e.com/image.png width="100" height="100"]<br />
^ malformed tag, shouldn't match<br />
Not all of the lines above will match in the same way.
stderr
PHP Notice:  Undefined offset: 2 in /home/iBhf6B/prog.php on line 5
PHP Notice:  Undefined offset: 2 in /home/iBhf6B/prog.php on line 5