PHP 正则表达式来查找 JavaScript 变量


php regex to find javascript variables

我正在搜索的文本包含vars (= OR :) { (the stuff I want }

在 = 和 { 之间只能是空格,并且可以包含换行符。

我将在 PHP 中将其转换为键/值数组。

这是我正在尝试的,它不会导致任何匹配:

$str = "vars = {'first' : 'joe', 'last' : 'smith' };";
preg_match("/^vars's='s'{(.*)'}/",$str, $matches);
echo $matches[0];

另一个应匹配的字符串:

$str = "vars : {'first' : 'joe', 'last' : 'smith' };";

也许你可以获取 { } 中的所有内容,然后让 JSON 解析器为您完成其余的工作。

$str = 'vars = {"first" : "joe", "last" : "smith" };';
preg_match("/'{.*'}/",$str, $matches);
var_dump(json_decode($matches[0]));
object(stdClass)#1 (2) {
  ["first"]=>
  string(3) "joe"
  ["last"]=>
  string(5) "smith"
}

此方法仅适用于有效的 JSON ofc。

要匹配它,请使用:

preg_match_all('/^vars's[=:]'s{(.*)};$/m', $str, $matches, PREG_PATTERN_ORDER);
$matches = $matches[0];