PHP Regular Expression提取JSON数据

时间:2014-10-16 16:03:09

标签: php regex

我有以下字符串:

window['test'] = false; 
window['options'] = true; 
window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"};`

我如何在window['data']中提取JSON数据?我提供的示例数据只是真实存在的一小部分样本。 可能window['data']之前和/或之后有更多数据。

我试过这个,但没有运气:

preg_match( '#window["test"] = (.*?);\s*$#m', $html, $matches );

3 个答案:

答案 0 :(得分:1)

我可以看到几个问题。

  1. 您的字符串使用单引号:window['test']而不是window["test"],这是您在正则表达式中使用的。这意味着您应该使用双引号括起正则表达式(或转义引号)。

  2. 您的正则表达式具有未转义的括号,用于创建字符类。您应该使用\[而不是[

  3. 您说您正在寻找data,但正则表达式会查找test

  4. 在正则表达式的末尾有一个$,这意味着如果在匹配的位之后除了空格之外什么都没有,那么你就不会匹配。

  5. 此外,您的数据似乎不完整,最后有一些缺少括号,但我认为这只是一个复制粘贴错误。

    所以我会尝试:

    php > preg_match("#window\['data'\]\s*=\s*(.*?);#", $html, $matches); php > print_r($matches); Array ( [0] => window['data'] = {"id":2345,"stuff":[{"id":704,"name":"test"}; [1] => {"id":2345,"stuff":[{"id":704,"name":"test"} )

    当然,您必须使用json_decode()将JSON字符串($matches[1])转换为可以使用的对象或关联数组。

答案 1 :(得分:0)

您可以使用此正则表达式:

window\['data'\]\s*=\s*(.*?);

<强> Working demo

enter image description here

比赛信息是:

MATCH 1
1.  [67-111]    `{"id":2345,"stuff":[{"id":704,"name":"test"}`

正如regex101建议您可以拥有这样的代码:

$re = "/window\\['data'\\]\\s*=\\s*(.*);/"; 
$str = "window['test'] = false; window['options'] = true; window['data'] = {\"id\":2345,\"stuff\":[{\"id\":704,\"name\":\"test\"};"; 

preg_match_all($re, $str, $matches);

答案 2 :(得分:0)

您可以使用正则表达式解析window数据:

/^window\[['"](\w+)['"]\]\s*=\s*(.+);\s*$/m

然后您可以通过window数据结构中的原始索引检索这些片段,并在闲暇时解析JSON。

$data = <<<_E_
window['test'] = false;
window['options'] = true;
window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"}]};
_E_;
$regex = <<<_E_
/^window\[['"](\w+)['"]\]\s*=\s*(.+);\s*$/m
_E_; // SO syntax highlighting doesnt like HEREDOCs "

if( preg_match_all($regex,$data,$matches) > 0 ) {
    var_dump($matches);
    $index = array_search('data',$matches[1]);
    if( $index !== 0 ) {
        var_dump(json_decode($matches[2][$index]));
    } else { echo 'no data section'; }
} else { echo 'no matches'; }

输出:

// $matches
array(3) {
  [0]=>
  array(3) {
    [0]=>    string(24) "window['test'] = false; "
    [1]=>    string(26) "window['options'] = true; "
    [2]=>    string(69) "window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"}]};"
  }
  [1]=>
  array(3) {
    [0]=>    string(4) "test"
    [1]=>    string(7) "options"
    [2]=>    string(4) "data"
  }
  [2]=>
  array(3) {
    [0]=>    string(5) "false"
    [1]=>    string(4) "true"
    [2]=>    string(51) "{ "id" : 2345, "stuff": [{"id":704,"name":"test"}]}"
  }
}
// decoded JSON
object(stdClass)#1 (2) {
  ["id"]=>      int(2345)
  ["stuff"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (2) {
      ["id"]=>      int(704)
      ["name"]=>    string(4) "test"
    }
  }
}

注意:我在您的示例中将JSON修复为有效,因此它实际上会解析。