Search code examples
phpregextemplatesreplaceplaceholder

Replace curly-braced placeholders containing dot-delimited values with values from a 2d array


I have a paragraph of text like:

$paragraph = "Hello there {Customer.name},
You are {Customer.age} years old. You were born in the year {Customer.birthdate}";

I want to replace this with contents of an array such as

array('Customer' => array('name'=>'Tom', 'age'=>8, 'birthdate'=>'1980-01-01'))

My question is what is the best way to go about doing this? If you have a suggestion on how to format the text that would also be helpful. I am guessing you would have to use some kind of regular expression, maybe preg_filter() or preg_replace().


Solution

  • http://php.net/manual/en/function.sprintf.php

    $format_string = "Hello there %s, You are %d years old. You were born in the year %s";
    $paragraph = sprintf($format_string, 
                         $customer['name'], 
                         $customer['age'], 
                         $customer['birthdate']);