0

I want to replace a string with a corresponding value from an array. So for example:

$array=array(
    'food'=>'cornbread',
    'day'=>'wednesday'
);

$string='My favorite food is {food}';

This isn't right:

$string=preg_replace("/{(.*?)}/",$c[1],$string);

What is the best way to do this?

pg.
  • 2,503
  • 4
  • 42
  • 67

1 Answers1

0

str_replace() works with arrays. Search on the keys and replace with the values:

$string = str_replace(array_keys($array), $array, $string);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87