Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 716
Casebash Avatar asked Oct 07 '11 04:10

Casebash


People also ask

What is a PHP template?

A PHP template engine is a way of outputting PHP in your HTML without using PHP syntax or PHP tags. It's supposed to be used by having a PHP class that will send your HTML the variables you want to display, and the HTML simply displays this data.

Does Python have template strings?

Template string is another method used to format strings in Python. In comparison with %operator, . format() and f-strings, it has a (arguably) simpler syntax and functionality.


1 Answers

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 
like image 183
James Coyle Avatar answered Sep 20 '22 08:09

James Coyle