user1788736 user1788736 - 1 month ago 27x
JSON Question

How to replace json key value using php regular expression?

I have a invalid json string like this :

"title_en":"first season",
"description_en":"This is spring category "
"description1":"some text for" description here",
"description2":"some text for" description here2",
"title":"first title here"

"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.



Try this code:

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

Solution with regex:

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