Trainy
Trainy

Reputation: 13

RegExp (preg_match) for variables

I'm trying to match the variables out of a script, for example this line:

Hello World, this is a Test. $i = 1, $sString = "Test"

So I want to get $i and $sString.

I tried many different patterns, e.g. $pattern = '/(\$\w+)/';. I only get $i twice but not $sString.

As you can see here.

Upvotes: 1

Views: 60

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

You only get one match $i. The reason that there are two results is that the parentheses capture the result and that capture is returned as well (you could use this to return submatches, like everything except the leading $). To get all matches, use preg_match_all. And remove the parentheses if you don't need them (and you'll never need them if they just wrap the entire expression):

preg_match_all('/[$]\w+/', $subject, $matches);

Note that the resulting array is one level deeper, so you'll find your array of matches in $matches[0].

Demo

Upvotes: 1

Related Questions