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.
The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.
%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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With