Php 如何用变量动态缝合模板?
我试图让用户定义要传递到字符串中的值 如何在不使用eval()或静态定义所有变量的情况下,用模板动态缝合一些变量 我正在寻找一个小脚印解决方案。不包括整个模板引擎或库Php 如何用变量动态缝合模板?,php,arrays,templates,Php,Arrays,Templates,我试图让用户定义要传递到字符串中的值 如何在不使用eval()或静态定义所有变量的情况下,用模板动态缝合一些变量 我正在寻找一个小脚印解决方案。不包括整个模板引擎或库 <?php // Create a template $tpl = " ... {$var['a']} ... "; // User defined content // State variables $var = [ 'a' => 1, 'b' => 2, ]; // Sti
<?php
// Create a template
$tpl = " ... {$var['a']} ... "; // User defined content
// State variables
$var = [
'a' => 1,
'b' => 2,
];
// Stitch
echo $tpl;
只需更改替换格式:
<?php
$tpl = "Dear @name@, I would love to come to @location@.";
$subs =
[
'@name@' => 'Julian',
'@location@' => 'Freetown'
];
echo strtr($tpl, $subs);
或者,围绕strtr的包装器:
function template($template_str, array $vars) {
foreach($vars as $k => $v)
$substitutes['@'.$k.'@'] = $v;
return strtr($template_str, $substitutes);
}
$tpl = "Dear @name@, I would love to come to @location@.";
$subs = [
'name' => 'Julian',
'location' => 'Freetown'
];
echo template($tpl, $subs);
支持递归数组是什么意思?感谢您尝试回答这个问题。此解决方案不考虑递归数组。@tim,在您的问题中解释您希望如何处理它们。这还不清楚。
Dear Julian, I would love to come to Freetown.
function template($template_str, array $vars) {
foreach($vars as $k => $v)
$substitutes['@'.$k.'@'] = $v;
return strtr($template_str, $substitutes);
}
$tpl = "Dear @name@, I would love to come to @location@.";
$subs = [
'name' => 'Julian',
'location' => 'Freetown'
];
echo template($tpl, $subs);