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

Casebash picture Casebash · Oct 7, 2011 · Viewed 54.8k times · Source

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?

Answer

James Coyle picture James Coyle · Mar 9, 2018

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