-1

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

MGM
  • 223
  • 1
  • 13

2 Answers2

1

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
Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
1

Check this,

$data = '{
  "lbl_name":"Your name",
  "dynamic_name":"Hi, {{ name 1 }}, {{ name 2 }} and {{ name 3 }}"
}';

$data = json_decode($data, true);

$dynamic_name = $data['dynamic_name'];
$lbl_name = $data['lbl_name'];

preg_match_all('/{{ (.*?) }}/', $dynamic_name, $display);
$dynamic_name = "Hi ".$display[1][0].", ".$display[1][1]." and ".$display[1][2]; 

$newArray = array('lbl_name'=> $lbl_name, 'dynamic_name'=>$dynamic_name);
print_r($newArray);
Gayan
  • 2,845
  • 7
  • 33
  • 60