繁体   English   中英

用数组中的某些元素替换字符串(PHP)

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

我有一段文字像:

$ paragraph =“您好,{Customer.name},您{Customer.age}岁。您出生于{Customer.birthdate}年。”

我想用例如数组的内容替换它

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

我的问题是执行此操作的最佳方法是什么? 如果您对如何设置文本格式有任何建议,那也将有所帮助。 我猜你将不得不使用某种正则表达式,也许是preg_filter或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']);

您将为此使用preg_replace_callback() 只需在\\{(.+)\\.(.+)\\}上进行匹配,并适当地索引数组即可。

如果$ paragraph中句子的格式始终与花括号语法一致,则可以使用str_replace()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM