I've got the following JSON string:
{
"time":"321321545646",
"documents":[
{"name":"name1","body":"HASH_BASE64 1"},
{"name":"name2","body":"HASH_BASE64 2"}
]
}
In real production use, the "HASH BASE64" will be base64 encoded string. How can I replace content of each "body" tag with string = "LONGSTRING", to receive something like this:
{
"time":"321321545646",
"documents":[
{"name":"name1","body":"LONGSTRING"},
{"name":"name2","body":"LONGSTRING"}
]
}
?
You probably shouldn't do it with regular expressions but by decoding, changing the data and encoding again:
$data = json_decode($json);
for($i = 0; $i < count($data->documents); $i++) {
$data->documents[$i]->body = "LONGSTRING";
}
$json = json_encode($data);
You shouldn't use regular expressions to modify JSON data - PHP has native functions for parsing and encoding it. See 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);
You Don't Need preg-replace()
Just Decode Your json by json_decode()
Then Loop Through The json Document And change Each Document data Like So:
$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);
This Is The Output :
{#229 ▼
+"time": "321321545646"
+"documents": array:2 [▼
0 => {#228 ▼
+"name": "name1"
+"body": "LONGSTRING"
}
1 => {#227 ▼
+"name": "name2"
+"body": "LONGSTRING"
}
]
}