Replacing a string with certain elements in an array (PHP)
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.
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']);
You'll want to use preg_replace_callback()
for this. Just match on \{(.+)\.(.+)\}
and index the array appropriately.
If the format of the sentence in $paragraph will always be consistent with the curly brace syntax, you could use str_replace().
精彩评论