1

我正在使用以下代码来匹配以“$”开头的脚本中的所有变量,但是我希望结果不包含重复项,即不同/唯一:

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

有什么建议吗?

4

3 回答 3

8

用于array_unique从输出数组中删除重复项:

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

但我希望你不要试图用它来解析 PHP。用于token_get_all获取给定 PHP 代码的令牌。

于 2010-02-16T20:43:36.227 回答
2

不要用正则表达式那样做。在您将它们全部收集到您的$variables. 例如,使用array_uniqueGumbo 提到的。

此外,在这些情况下,您的正则表达式会做什么:

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

所有三个“变量”($not$var$this都不是变量,但会与您的正则表达式匹配。

于 2010-02-16T20:45:51.713 回答
1

试试下面的代码:

preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables);
于 2010-02-16T20:45:07.430 回答