How to replace placeholders with actual values?

后端 未结 6 960
逝去的感伤
逝去的感伤 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:55

    You can do this most easily with the /e modifier of preg_replace:

    $data["name"] = "Johnny";
    $data["age"] = "20";
    
    $string = "Hello my name is {name} and I'm {age} years old.";
    
    echo preg_replace('/{(\w+)}/e', '$data["\\1"]', $string);
    

    See it in action.

    You might want to customize the pattern that matches the replacement strings (which here is {\w+}: one or more alphanumeric characters or underscores between curly brackets). Putting it into a function is trivial.

提交回复
热议问题