PHP关联数组值替换字符串变量

I have a string as:

$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";

and I have an array like that and it will be always in that format.

$array = array(
   'name' => 'Jon',
   'detail' => array(
     'country' => 'India',
     'age' => '25'
  )
);

and the expected output should be like :

My name is Jon. I live in India and age is 25

So far I tried with the following method:

$string = str_replace(array('{name}','{detail.country}','{detail.age}'), array($array['name'],$array['detail']['country'],$array['detail']['age']));

But the thing is we can not use the plain text of string variable. It should be dynamic on the basis of the array keys.

You can use a foreach to achieve that :

foreach($array as $key=>$value)
{
  if(is_array($value))
  {
      foreach($value as $key2=>$value2)
      {
           $string = str_replace("{".$key.".".$key2."}",$value2,$string); 
      }
  }else{
      $string = str_replace("{".$key."}",$value,$string);
  }
}
print_r($string);

The above will only work with a depth of 2 in your array, you'll have to use recurcivity if you want something more dynamic than that.

You can use preg_replace_callback() for a dynamic replacement:

$string = preg_replace_callback('/{([\w.]+)}/', function($matches) use ($array) {
    $keys = explode('.', $matches[1]);
    $replacement = '';

    if (sizeof($keys) === 1) {
        $replacement = $array[$keys[0]];
    } else {
        $replacement = $array;

        foreach ($keys as $key) {
            $replacement = $replacement[$key];
        }
    }

    return $replacement;
}, $string);

It also exists preg_replace() but the above one allows matches processing.

echo "my name is ".$array['name']." .I live in ".$array['detail']['countery']." and my age is ".$array['detail']['age'];

Here's a recursive array handler: http://phpfiddle.org/main/code/e7ze-p2ap

<?php

function replaceArray($oldArray, $newArray = [], $theKey = null) {
    foreach($oldArray as $key => $value) {
        if(is_array($value)) {
            $newArray = array_merge($newArray, replaceArray($value, $newArray, $key));
        } else {
            if(!is_null($theKey)) $key = $theKey . "." . $key;
            $newArray["{" . $key . "}"] = $value;
        }
    }
    return $newArray;
}

$array = [
   'name' => 'Jon',
   'detail' => [
     'country' => 'India',
     'age' => '25'
  ]
];
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";

$array = replaceArray($array);

echo str_replace(array_keys($array), array_values($array), $string);

?>