preg_match_all确保不同/唯一的结果

时间:2010-02-16 20:41:56

标签: php preg-match-all

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

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

有什么建议吗?

3 个答案:

答案 0 :(得分:5)

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

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

但我希望你不要试图解析PHP。使用token_get_all获取给定PHP代码的标记。

答案 1 :(得分:2)

请勿使用正则表达式执行此操作。在$variables中收集所有内容之后,只需使用正常的编程逻辑/操作对其进行过滤即可。例如,使用array_unique作为Gumbo提到的。

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

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

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

答案 2 :(得分:1)

请尝试以下代码:

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