PHP - 如何将命名变量放入字符串中并在变量之前定义字符串

2023-12-22

我正在寻找 php 相当于pythons %操作员 https://stackoverflow.com/a/2962966/1695680.

# PYTHON Example
foo = 'variable_string'
baz = 'characters'

new_string = 'my %(foo)s of %(baz)s' % locals()

我的模糊 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执行。
  • 我不能假设我能够使用 php 5.3 之后的任何内容
  • 我不介意传递一个明确的array('$variable_name' => $variable_name)
  • 在不定义新函数的情况下执行此操作的要点。

最后注意:我已经为我的特定用例构建了一个解决方法,但是它不能满足问题。


一个好的方法是strtr http://us.php.net/strtr:

strtr('<h1>{foo}</h1><h2>{bar}</h2>', array(
  '{foo}' => $foo,
  '{bar}' => $bar,
));

您还可以使用get_defined_vars() http://us.php.net/get_defined_vars获取当前范围内可访问的变量数组,尽管我个人更喜欢显式枚举。


使用的微妙优势之一strtr over str_replace就是它strtr will not搜索字符串中已替换的部分以进行进一步的替换。的手册页str_replace状态:

Because str_replace()从左到右替换,在进行多次替换时,它可能会替换先前插入的值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP - 如何将命名变量放入字符串中并在变量之前定义字符串 的相关文章

随机推荐