解析字符串中的内联变量的更优雅的方法 [英] More elegant way to parse inline variables in strings
本文介绍了解析字符串中的内联变量的更优雅的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我有这个:
function parse_string($string, $variables){
extract($variables);
return eval('return "'. addcslashes($string, '"') .'";');
}
因此我可以输入以下字符串:
So I can input this string:
'Hi {$name}, my name is {$own_name}'
与此数组一起:
array('name' => 'John', 'own_name' => 'Tom')
并将其取回:
'Hi John, my name is Tom'
我从不喜欢这种eval()
方法,但是它可以工作并且速度快(至少比正则表达式快).
I've never liked this eval()
approach but it works and it's fast (faster than regex at least).
问题:在PHP5中,有没有一种更优雅的方法(比使用regex更快)?
Question: Is there a more elegant way to do this (faster than using regex) in PHP5?
推荐答案
foreach ($variables as $variable => $value) {
$string = str_replace('{$' . $variable . '}', $value, $string);
}
这篇关于解析字符串中的内联变量的更优雅的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文