Skip to content
Advertisement

Capturing text between two groups of square brackets in 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?

Advertisement

Answer

Maybe with this simply expression:

preg_match('/](.*)[/', 'test test [foo] bar [/foo] test', $match);
echo trim($match[1]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement