开发者

preg_match_all ensure distinct/unique results

I am using the following code to match all variab开发者_如何学Goles 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?


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜