将包含点分隔值的大括号占位符替换为二维数组中的值

问题描述 投票:0回答:3

我有一段文字,例如:

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

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

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

我的问题是执行此操作的最佳方法是什么?如果您对如何格式化文本有建议,那也会很有帮助。我猜你必须使用某种正则表达式,也许

preg_filter()
preg_replace()

php regex templates replace placeholder
3个回答
2
投票

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']);

2
投票

为此,您需要使用

preg_replace_callback()
。只需匹配
\{(.+)\.(.+)\}
并适当地索引数组即可。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.