I need a function that replace every variable_name inside \'{}\' with the correct variable. Something like this:
$data[\"name\"] = \"Johnny\";
$data[\"age\"
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.