PHP preg_replace是JSON内容的一部分

时间:2017-08-24 14:43:54

标签: php json

我有以下JSON字符串:

{
    "time":"321321545646",
    "documents":[
        {"name":"name1","body":"HASH_BASE64 1"},
        {"name":"name2","body":"HASH_BASE64 2"}
    ]
}

在实际生产中使用,“HASH BASE64”将是base64编码的字符串。 如何使用string =“LONGSTRING”替换每个“body”标记的内容,以接收以下内容:

{
    "time":"321321545646",
    "documents":[
        {"name":"name1","body":"LONGSTRING"},
        {"name":"name2","body":"LONGSTRING"}
    ]
}

3 个答案:

答案 0 :(得分:1)

你不需要preg-replace()只需通过json_decode()

解码你的json

然后循环浏览json文档并更改每个文档数据,如此:

$json = json_decode('{
    "time":"321321545646",
    "documents":[
        {"name":"name1","body":"HASH_BASE64 1"},
        {"name":"name2","body":"HASH_BASE64 2"}
    ]
}');
foreach ($json->documents as $document){
    $document->body = "LONGSTRING";
}
dump($json);

这是输出:

{#229 ▼
  +"time": "321321545646"
  +"documents": array:2 [▼
    0 => {#228 ▼
      +"name": "name1"
      +"body": "LONGSTRING"
    }
    1 => {#227 ▼
      +"name": "name2"
      +"body": "LONGSTRING"
    }
  ]
}

答案 1 :(得分:0)

您可能不应该使用正则表达式,而是通过解码,再次更改数据和编码:

$data = json_decode($json);

for($i = 0; $i < count($data->documents); $i++) {
    $data->documents[$i]->body = "LONGSTRING";
}

$json = json_encode($data);

答案 2 :(得分:0)

您不应该使用正则表达式来修改JSON数据 - PHP具有用于解析和编码它的本机函数。见http://php.net/manual/en/ref.json.php

<?php
$json = '{
    "time":"321321545646",
    "documents":[
        {"name":"name1","body":"HASH_BASE64 1"},
        {"name":"name2","body":"HASH_BASE64 2"}
    ]
}';

// Decode JSON into a native PHP object structure
$decoded = json_decode($json);

// Loop over each element, and modify the body
$decoded->documents = array_map(function ($document) {
    $document->body = 'LONGSTRING';
    return $document;
}, $decoded->documents);

// Re-encode
echo json_encode($decoded);