Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 StringTemplateEngine;

$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...