我正在使用以下代码来匹配以“$”开头的脚本中的所有变量,但是我希望结果不包含重复项,即不同/唯一:
preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
有什么建议吗?
我正在使用以下代码来匹配以“$”开头的脚本中的所有变量,但是我希望结果不包含重复项,即不同/唯一:
preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
有什么建议吗?
用于array_unique
从输出数组中删除重复项:
preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables[0]);
但我希望你不要试图用它来解析 PHP。用于token_get_all
获取给定 PHP 代码的令牌。
不要用正则表达式那样做。在您将它们全部收集到您的$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
都不是变量,但会与您的正则表达式匹配。
试试下面的代码:
preg_match_all('/\$[a-zA-Z0-9]+/', $code, $variables);
$variables = array_unique($variables);