phpstringtemplatestemplate-variables

Does PHP have a feature like Python's template strings?


Python has a feature called template strings.

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

I know that PHP allows you to write:

"Hello $person"

and have $person substituted, but the templates can be reused in various sections of the code?


Solution

  • You could also use strtr:

    $template = '$who likes $what';
    
    $vars = array(
      '$who' => 'tim',
      '$what' => 'kung pao',
    );
    
    echo strtr($template, $vars);
    

    Outputs:

    tim likes kung pao