I have a template which has certain fields which are to be replaced with a given value.
The fields each have a name which is enclosed with curly brackets. For instance: {address}
The replacement values are included in an array where the index is the name. For instance array('address'=>'101 Main Street', 'city’=>'New York')
I am using the following, and it works great (most of the time)
$template_new= preg_replace('/\{\?(\w+)\?\}/e', '$array["$1"]', $template);
Problem is if I have a {bad_name} which is not in the array, I get the following error:
Notice: Undefined index: xxx in
/var/www/classes/library.php(860) : regexp code on line
1
My desire is to leave these in place without changing them.
My first thought was to replace $array["$1"] with (isset($array["$1"])?$array["$1"]': '{'.$1.'}'), but it didn’t work.
I also tried try/catch, but it also didn’t help
Please provide any recommendations. Thank you
You’d have better luck with preg_replace_callback() and doing something like this:
Keep in mind, I typed that in off the top of my head, so there may be bugs.
Here’s how you’d do much the same thing with anonymous functions, assuming you’re able to use them:
Much more compact!