preg_match_all ensure distinct/unique results

為{幸葍}努か 提交于 2019-12-23 04:00:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!