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?
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?
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.
Maybe with this simply expression:
preg_match('/\](.*)\[/', 'test test [foo] bar [/foo] test', $match);
echo trim($match[1]);
I guess back references will be helpful if you care about exactly the matching of the tags. Use regex:
$text = 'test test [foo] bar [/foo] test';
preg_match('/\[([^\]]+)\](.*?)\[\/\1\]/', $text, $matches);
do_work($matches[2]); // maybe trim it
// and more
Let me explain it to you. First, I add (...)
in the first part of your pattern (matching [xxx]
) to make it a subpattern. Then we can refer to its matches using \1
(while 1
is the numeric position of the subpattern, counted from left and starting from 1). You can see the link above for further information. (My English is poor so the explanation may be unclear.)
Also, you can give the subpattern a name (which is called named subpattern) like:
/\[(?P<tag_name>[^\]]+)\](.*?)\[\/(?P=tag_name)\]/is
From PHP Manual:
(?P<name>pattern)
. This subpattern will then be indexed in the matches array by its normal numeric position and also by name. There are two alternative syntaxes (?<name>pattern)
and (?'name'pattern)
.(?P=name)
, \k<name>
, \k'name'
, \k{name}
, \g{name}
, \g<name>
or \g'name'
.Be careful when the same kind of tags can be nested. Think about:
test
test
[foo][foo]bar[/foo][/foo]
test
Then we may need to see Regular expression for nested tags (innermost to make it easier).