【问题标题】:PHP regular expressions [duplicate]PHP正则表达式[重复]
【发布时间】:2016-01-12 14:39:14
【问题描述】:

如何预匹配 total_count 来自 php 中的这段代码

{
   "data": [
      {
         "name": "Baptiste Chimay",
         "administrator": false,
         "id": "10153820811316460"
      },
   "summary": {
      "total_count": 4956
   }
}

我试过了,但没有得到任何数据

$url = ('the url i want');
                $result = json_decode($url);
    $likes = preg_match("'total_count (.*?),'si", file_get_contents($url), $matches);
print_r($url);

【问题讨论】:

  • 看起来像(部分)json - 这是该网址的全部输出吗?
  • 不是整个输出
  • 请添加整个输出。 PHP 原生支持 json,所以正则表达式不是最好的解决方案

标签: php preg-match file-get-contents


【解决方案1】:

那是json数据,可以使用json_decode创建一个php数组:

$data = json_decode(file_get_contents($myurl), true);

echo $data['summary']['total_count']; //outputs 4956

【讨论】:

    【解决方案2】:

    只需转义引号:

    preg_match("/total_count\"\:(.*?)/i", file_get_contents($myurl), $matches);
    //               here __^
    

    但是,你不需要转义分号

    preg_match("/total_count\":(.*?)/i", file_get_contents($myurl), $matches);
    

    你也可以用单引号代替双引号:

    preg_match('/total_count":(.*?)/i', file_get_contents($myurl), $matches);
    

    并将.*? 更改为[^"]+

    preg_match("/total_count\":([^"]+)/i", file_get_contents($myurl), $matches);
    

    你也可以用单引号代替双引号:

    preg_match('/total_count":(\d+)/i', file_get_contents($myurl), $matches);
    

    【讨论】:

    • 我实际上会从 [^"] 更改为 d+
    • @mloureiro:你说得对
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多