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

时间:2019-03-08 15:22:29

标签: php str-replace

我的字符串为:

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

,预期输出应为:

  

我叫乔恩。我住在印度,年龄25岁

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

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

但是问题是我们不能使用字符串变量的纯文本。根据阵列键应该是动态的。

4 个答案:

答案 0 :(得分:1)

您可以使用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的情况下使用,如果您想要比此更动态的内容,则必须使用递归。

答案 1 :(得分:1)

您可以使用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(),但是上面的一个允许进行匹配处理。

答案 2 :(得分:1)

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

?>

答案 3 :(得分:-3)

echo“我的名字是”。$ array ['name']。“。我住在”。$ array ['detail'] ['countery']。“,我的年龄是”。$ array ['detail '] ['age'];

相关问题