正则表达式查找最后出现的方括号的内容

Hi Everybody,

I'm Currently using preg_match and I'm trying to extract some informations enclosed in square brackets.

So far, I have used this:

/\[(.*)\]/

But I want it to be only the content of the last occurence - or the first one, if starting from the end!

In the following:

string = "Some text here [value_a] some more text [value_b]"

I need to get:

"value_b"

Can anybody suggest something that will do the trick?

Thanks!

Match against:

/.*\[([^]]+)\]/

using preg_match (no need for the _all version here, since you only want the last group) and capture the group inside.

Your current regex, with your input, would capture value_a] some more text [value_b. Here, the first .* swallows everything, but must backtrack for a [ to be matched -- the last one in the input.

If you are only expecting numbers/letter (no symbols) you could use \[([\w\d]+)\] with preg_match_all() and pull the last of the array as the end variable. You can add any custom symbols by escaping them in the character class definition.