preg_match_all ensure distinct/unique results

半腔热情 提交于 2019-12-07 04:40:33

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