开发者

Replacing a string with certain elements in an array (PHP)

开发者 https://www.devze.com 2022-12-19 00:18 出处:网络
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 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().

0

精彩评论

暂无评论...
验证码 换一张
取 消