我正在寻找相当于pythons %运算符的php .
# PYTHON Example
foo = 'variable_string'
baz = 'characters'
new_string = 'my %(foo)s of %(baz)s' % locals()
Run Code Online (Sandbox Code Playgroud)
我模糊的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()
);
}
...
}
Run Code Online (Sandbox Code Playgroud)
magically_put_variables_in_string实现.array('$variable_name' => $variable_name)最后注意:我已经为我的特定用例构建了一个解决方案,但它不能满足这个问题.
DCo*_*der 12
一个好方法是strtr:
strtr('<h1>{foo}</h1><h2>{bar}</h2>', array(
'{foo}' => $foo,
'{bar}' => $bar,
));
Run Code Online (Sandbox Code Playgroud)
您还可以使用get_defined_vars()获取当前作用域中可访问的变量数组,但我个人更喜欢显式枚举.
对使用的细微优点strtr过str_replace是strtr将不搜索的字符串的已取代的部分,用于进一步的替代品.str_replace州的手册页:
因为
str_replace()从左到右替换,所以在执行多次替换时,它可能会替换先前插入的值.