- 此问题在此处已有答案**:
what is the efficient way to parse a template like this in php?(3个答案)
str_replace() with associative array(5个答案)
PHP - Replacing multiple sets of placeholders while looping through arrays(1个答案)
How do I use preg_replace in PHP with {{ mustache }}(1个答案)
(13个答案)
昨天关门了。
如何编写自定义php函数,通过传递函数参数将变量替换为值?
$template = "Hello, {{name}}!";
$data = [
'name'=> 'world'
];
echo replace($template, $data);
function replace($template, $data) {
$name = $data['name'];
return $template;
}
回显替换($模板,$数据);必须返回"你好,世界!"谢谢!
2条答案
按热度按时间n1bvdmb61#
一种方法是使用内置的
str_replace
函数,如下所示:这将循环数据数组并将键替换为值。
os8fio9y2#
您可以使用
preg_replace_callback_array
来执行正则表达式搜索并使用回调进行替换。这个解决方案适用于多个变量,它解析整个文本,并交换每个指定的变量。
demo here