在PHP中捕获两组方括号之间的文本

I need some way of capturing the text between two group of square brackets. So for example, the following string:

test test [foo] bar [/foo] test

I need to output "bar", but 'bar' is a variable word

How can I get the output I need?

Maybe with this simply expression:

preg_match('/\](.*)\[/', 'test test [foo] bar [/foo] test', $match);
echo trim($match[1]);

preg_match('/\[([^\]]+)\](.*?)\[\/\1\]/', $text)

Using a backreference to match the first square brackets tag to it's ending tag. Note this won't work if you want to allow nesting of the same tag, or treating nested tags as anything other then plain text.