我正在寻找pythons%
运算符的php等价物。
# PYTHON Example
foo = 'variable_string'
baz = 'characters'
new_string = 'my %(foo)s of %(baz)s' % locals()
我的Vague php上下文:
注意:这是为了演示为什么要执行此操作,它不反映任何代码。
// PHP Example context
class Controller {
...
// Singles quotes used in intentionally
// This template string is meant to be overloadable.
public $template = '<h1>{$title}</h1><h2>{$subheading}</h2>';
....
}
class View {
...
public function render($template) {
$title = 'variable string';
$subheading = 'some other variable stuff';
// Example of the python operator
return magically_put_variables_in_string(
$template,
magically_get_named_variables_from_scope()
);
}
...
}
magically_put_variables_in_string
实现。array('$variable_name' => $variable_name)
最后说明:我已经为我的特定用例构建了解决方法,但是它不能满足这个问题。
一个好的方法是strtr
:
strtr('<h1>{foo}</h1><h2>{bar}</h2>', array(
'{foo}' => $foo,
'{bar}' => $bar,
));
您也可以使用get_defined_vars()
获取在当前范围内可访问的变量数组,尽管我个人更喜欢显式枚举。
对使用的细微优点strtr
过str_replace
是strtr
将不搜索的字符串的已取代的部分,用于进一步的替代品。str_replace
状态手册页:
由于
str_replace()
从左到右进行替换,因此在进行多次替换时,它可能会替换先前插入的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句