繁体   English   中英

PHP正则表达式提取JSON数据

[英]PHP Regular Expression to extract JSON data

我有以下字符串:

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 );

我可以看到几个问题。

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

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

  3. 您说您正在寻找data但您的正则表达式则寻找test

  4. 您在正则表达式的末尾有一个$ ,这意味着如果匹配的位后面没有空格,那么您将不匹配。

另外,您的数据似乎不完整,结尾处缺少一些括号,但是我认为这只是一个复制粘贴错误。

所以我会尝试:

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] )转换为可以使用的对象或关联数组。

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

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

工作演示

在此处输入图片说明

比赛信息是:

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);

您可以使用正则表达式解析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固定为有效,因此它将进行实际解析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM