user1788736 user1788736 - 3 months ago 63
JSON Question

How to replace json key value using php regular expression?

I have a invalid json string like this :

{
"cat":{
"id":"1234567",
"source_id":null,
"title_en":"first season",
"description_en":"This is spring category "
},
"videos":[
{
"id":"312412343",
"url":"\/2015-07-17\/1abcd.mp4",
"img":"image\/44\/\/2015-07-17\/1abcd.jpg",
"description1":"some text for" description here",
"description2":"some text for" description here2",
"title":"first title here"

},
{
"id":"2342343",
"url":"\/2015-07-16\/2dcdeg.mp4",
"img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
"description1":"some other text here" for description ",
"description2":"some other text here" for description2 ",
"title":"second title here"

}
]
}


I want to change the value of description1 and description2 to word empty using regular expression. Could any one help me how to achieve this using regular expression ?Thanks.

"description1":"empty",
"description2":"empty",

Answer

Try this code:

$result = json_decode($json, true);
array_walk($result['videos'], function (&$item) {$item['description1'] = 'empty'; $item['description2'] = 'empty';});
$json = json_encode($result);
print_r($json);

Solution with regex:

print_r(preg_replace('/\"description(1|2)\"\:\".*?\"\,/s', '"description$1":"empty",',$json));
Comments