vsprintf or sprintf with named arguments, or simple template parsing in PHP

Jeremy S. picture Jeremy S. · Apr 18, 2011 · Viewed 21.9k times · Source

I'm searching for a way to use named arguments for sprintf or printf.

Example:

sprintf(
  'Last time logged in was %hours hours, 
   %minutes minutes, %seconds seconds ago'
  ,$hours,$minutes, $seconds
);

or via vsprintf and an associative array.

I have found some coding examples here

function sprintfn ($format, array $args = array())

http://php.net/manual/de/function.sprintf.php

and here

function vnsprintf( $format, array $data)

http://php.net/manual/de/function.vsprintf.php

where people wrote their own solutions.

But my question is, is there maybe an standard PHP solution out there to achieve this or is there another way, maybe with a simple PHP templating provided by PEAR, that I can achieve this by sticking to standard PHP?

Thanks for any help.

Answer

Nicolò Martini picture Nicolò Martini · Aug 14, 2013

I've written a small component exactly for this need. It's called StringTemplate. With it you can get what you want with a code like this:

$engine = new StringTemplate\Engine;

$engine->render(
   'Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago',
   [
      'hours' => '08',
      'minutes' => 23,
      'seconds' => 12,
   ]
);
//Prints "Last time logged in was 08 hours, 23 minutes, 12 seconds ago"

Hope that can help.