问题
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?
回答1:
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.
回答2:
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.
回答3:
Try the following code:
preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables);
来源:https://stackoverflow.com/questions/2276168/preg-match-all-ensure-distinct-unique-results