Question

I am using the following code to match all variables in a script starting with '$', however i would like the results to not contain duplicates, ie be distinct/unique:

preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);

Any advice?

Was it helpful?

Solution

Use array_unique to remove the duplicates from your output array:

preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables[0]);

But I hope you’re not trying to parse PHP with that. Use token_get_all to get the tokens of the given PHP code.

OTHER TIPS

Don't do that with regex. After you collected them all in your $variables, simply filter them using normal programming logic/operations. Using array_unique as Gumbo mentioned, for example.

Also, what will your regex do in these cases:

// this is $not a var
foo('and this $var should also not appear!');
/* and what about $this one? */

All three "variables" ($not, $var and $this) aren't variables, but will be matched by your regex.

Try the following code:

preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top