从JSON文件中获取特定文本

时间:2014-08-02 04:17:53

标签: php regex string

我在json文件中寻找这种类型的文本:

{"id":"*****number*******","name":"****namehere******"}

例如:

{"id":"100007015692915","name":"Ida Ka"}

JSON文件是一个复杂的JSON文件,看起来像这样(这是JSON文件的一部分):

  

updated_time":"2014-02-19T15:15:31+0000","likes":{"data":[{"id":"1487307502","name":"Svatava Dohnalov\u00e1"},{"id":"662920773","name":"Alena Al Hr\u010dkov\u00e1"},{"id":"100007015692915","name":"Ida Ka"},{"id":"100000533191263","name":"Zlati V\u00e1\u0148ov\u00e1"},{"id":"1658256962","name":"Ji\u0159\u00ed Jager"},{"id":"1054706643","name":"Pavla Bubikova Winter"}],"paging":

如何从JSON文件中恢复所有这些名称和ID,并将它们放在数组中?

我正在使用PHP,解决方案可能包括正则表达式。

3 个答案:

答案 0 :(得分:1)

您正在寻找json_decode

$json = '{"id":"100007015692915","name":"Ida Ka"}';
$arr = json_decode($json, true);

print_r($arr);

返回:

  

数组([id] => 100007015692915 [姓名] => Ida Ka)

答案 1 :(得分:1)

$data = json_decode($json, true);
$like_data = $data['likes']['data'];
foreach($like_data as $like) {
    echo "ID: {$like['id']} Name: {$like['name']}<br/>";
}

答案 2 :(得分:0)

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

"id":"(\d+)","name":"(.*?)"

检查此 working demo

中的捕获组
MATCH 1
1.  [65-75] `1487307502`
2.  [85-107]    `Svatava Dohnalov\u00e1`
MATCH 2
1.  [117-126]   `662920773`
2.  [136-162]   `Alena Al Hr\u010dkov\u00e1`
MATCH 3
1.  [172-187]   `100007015692915`
2.  [197-203]   `Ida Ka`
MATCH 4
1.  [213-228]   `100000533191263`
2.  [238-265]   `Zlati V\u00e1\u0148ov\u00e1`
MATCH 5
1.  [275-285]   `1658256962`
2.  [295-315]   `Ji\u0159\u00ed Jager`
MATCH 6
1.  [325-335]   `1054706643`
2.  [345-366]   `Pavla Bubikova Winter`