How to replace placeholders with actual values?

后端 未结 6 954
逝去的感伤
逝去的感伤 2021-01-07 12:00

I need a function that replace every variable_name inside \'{}\' with the correct variable. Something like this:

$data[\"name\"] = \"Johnny\";
$data[\"age\"         


        
6条回答
  •  既然无缘
    2021-01-07 12:43

    Here you go:

    $data["name"] = "Johnny";
    $data["age"] = "20";
    
    $string = "Hello my name is {name} and I'm {age} years old.";
    
    foreach ($data as $key => $value) {
    $string = str_replace("{".$key."}", $value, $string);
    }
    
    echo $string;
    

提交回复
热议问题