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

PHP associative array values replace string variable

我有一个字符串:

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

我有一个这样的数组,它将始终采用那种格式。

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

并且预期的输出应该是这样的:

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

到目前为止,我尝试了以下方法:

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

您可以使用 foreach 来实现:

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);

以上仅适用于深度为 2 的数组,如果您想要比这更动态的东西,则必须使用递归性。

您可以使用 preg_replace_callback() 进行动态替换:

$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);

它也存在 preg_replace() 但上面的允许匹配处理。

echo "my name is ".$array['name']." .我住在 ".$array['detail']['countery']." 和我的年龄是 ".$array['detail']['age'];

这是一个递归数组处理程序: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);

?>