Skip to content
Advertisement

Regex to find content of the last occurence of square brackets

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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement