How to match variables starting with $ with regex?

The point is this:

I have the following options:

['var1' => $var1, 'var2' => $obj->var1['asd']]
[ 'var1' => $var1, 'var2' => $obj->var1 ]
['var1' => $var1, 'var2' => $var2]

I need to match $var, $obj->var1['asd']and $obj->var1.

I went so far:

(\$[^,\s\]]+]?)

This almost works, but in the latter case this does not happen. See here in action: regex101.com/r/cI0yP0/3

UPDATE:

Thanks for all your answers. They all work great.

Now, as Joe pointed out, there may be other cases, such as the following.

['var' => $obj->var1->var2[2]->var3['test']->var4]
['var1' => $obj->var1[$obj2->var1['one']]]
['var2' => $obj[3]['var']]
['var3' => $obj->method()]
+4
source share
5 answers

This will allow you to capture any number of variables copied together, and will not include a moving square bracket:

 \$(?:(?:(?<!\$)->)?(?:[a-zA-Z]\w*(?:\[[^\[\]]+\])*)(?:\(\))?)+

This will lead to a capture $obj->var1->var2[2]->method1()->var3['test']['test2']->method2(), for example.

Demo

. .. $obj->var1[$obj2->var1['one']] ,

+2

. 3 , .

, :

(\$.*?),|(\$.*?\])\]|(\$.*?)\]

Regular expression visualization


, :

(\$.*?\]?)(?:,|\])

Regular expression visualization


. , .

(\$.*?\]?)[,\]]

Regular expression visualization

+3
(\$[\w]+(?:->[\w]+)?(?:\[.*?\])?)

DEMO

https://regex101.com/r/cI0yP0/6

+1

[...] part:

\$[^][,\s]+(?:\[[^]]*\])?

- RegEx

0

Try the following regex:

\$.+?(?=,|\s|\])(?:\](?=\]))?

See DEMO

Based on your input example, it will capture:

$var1
$obj->var1['asd']
$var1
$obj->var1
$var1
$var2
0
source

All Articles