我只是想让它{string}
变成$string
变量的值。
例如,考虑我有以下变量:
$car = 'Audi';
$speed = 'Fast';
$sentence = "The {car} goes {speed}";
我想要输出:The Audi goes Fast
这是我的代码无效:
$setting['leads_low_subject'] = '{dealer_name} has {leads_left} leads left!';
$dealer_name = 'My Test Dealer';
$leads_left = 6;
$subject = preg_replace('/\{([a-z]+)\}/e', "$$1", $setting['leads_low_subject']);
echo $setting['leads_low_subject'].'<br />';
echo "$subject";
这回应:
{dealer_name} has {leads_left} leads left!
{dealer_name} has {leads_left} leads left!
何时应该回应:
{dealer_name} has {leads_left} leads left!
My Test Dealer has 6 leads left!
为什么它无法正常工作?
答案 0 :(得分:4)
我看到的最快的方法是使用strtr():
$trans = array( '{car}' => 'Audi',
'{speed}' => 'Fast');
$result = strtr($sentence, $trans);
答案 1 :(得分:2)
好像你正在寻找一个穷人的模板引擎。您可以使用preg_replace_callback()
:
$tpl_vars = array(
'car' => 'Ford',
'speed' => 'fast'
);
$tpl = 'The {car} goes {speed}';
echo preg_replace_callback('/\{(.*?)\}/', function($match) use ($tpl_vars) {
return $tpl_vars[$match[1]];
}, $tpl);