MGM MGM - 19 days ago 5
PHP Question

How to replace JSON value using preg_replace?

This is my JSON file
sample.json

{
"lbl_name":"Your name",
"dynamic_name":"Hi, {{ name 1 }}, {{ name 2 }} and {{ name 3 }}"
}


and

$content = file_get_contents(sample.json);
$translate = json_decode$content, true);
$replaceContent = preg_replace('/\{{[^)]*\}}/', '%s', $translate);
print_r($replaceContent);


I am getting result

Array ( [lbl_name] => Your name [dynamic_name] => Hi %s )


I want result should be

Array ( [lbl_name] => Your name [dynamic_name] => Hi %s, %s and %s )


Thanks

Answer

your regex is greedy, therefore trying to match the biggest match it can get.

use the ?-control character to make your pattern non-greedy, meaning it matches the smallest match it can get:

$data = "Hi, {{ name 1 }}, {{ name 2 }} and {{ name 3 }}"
echo preg_replace('/{{[^)]*?}}/', '%s', $data);
//prints Hi, %s, %s and %s