Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 390
Jeremy S. Avatar asked Apr 18 '11 11:04

Jeremy S.


People also ask

What is the use of sprintf () function in PHP?

The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.

What does %s mean in PHP?

%s is a type specifier which will be replaced to valuable's value (string) in case of %s . Besides %s you can use other specifiers, most popular are below: d - the argument is treated as an integer, and presented as a (signed) decimal number.


2 Answers

Late to the party, but you can simply use strtr to "translate characters or replace substrings"

<?php  $hours = 2; $minutes = 24; $seconds = 35;  // Option 1: Replacing %variable echo strtr(     'Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago',     [         '%hours' => $hours,         '%minutes' => $minutes,         '%seconds' => $seconds     ] );  // Option 2: Alternative replacing {variable} echo strtr(     'Last time logged in was  {hours} hours, {minutes} minutes, {seconds} seconds ago',     [         '{hours}' => $hours,         '{minutes}' => $minutes,         '{seconds}' => $seconds     ] );  // More options: Of course you can replace any string.... 

outputs the following:

Last time logged in was 2 hours, 24 minutes, 35 seconds ago

like image 116
Alexander Taubenkorb Avatar answered Oct 21 '22 19:10

Alexander Taubenkorb


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.

like image 43
Nicolò Martini Avatar answered Oct 21 '22 18:10

Nicolò Martini