note 86068 added to function.sprintf
| From: | php at mikeboers dot com | Date: | Wed, 01 Oct 2008 20:42:54 +0000 |
| Subject: | note 86068 added to function.sprintf | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144953@lists.php.net to get a copy of this message | ||
And continuing on the same theme of a key-based sprintf...
I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of
Python's string formatting with a dictionary. The improvement over the several past attempts is
that this one still respects all of the formating options, as you can see in my example.
And the error handling is really crappy (just an echo). I just threw this together so do with it
what you will. =]
<?php
function sprintf_array($string, $array)
{
$keys = array_keys($array);
$keysmap = array_flip($keys);
$values = array_values($array);
while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
{
if (!isset($keysmap[$m[1]]))
{
echo "No key $m[1]\n";
return false;
}
$string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
}
array_unshift($values, $string);
var_dump($values);
return call_user_func_array('sprintf', $values);
}
echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));
?>
Cheers!
----
Server IP: 66.207.199.35
Probable Submitter: 208.124.157.118
----
Manual Page -- http://www.php.net/manual/en/function.sprintf.php
Edit -- https://master.php.net/note/edit/86068
Del: integrated -- https://master.php.net/note/delete/86068/integrated
Del: useless -- https://master.php.net/note/delete/86068/useless
Del: bad code -- https://master.php.net/note/delete/86068/bad+code
Del: spam -- https://master.php.net/note/delete/86068/spam
Del: non-english -- https://master.php.net/note/delete/86068/non-english
Del: in docs -- https://master.php.net/note/delete/86068/in+docs
Del: other reasons-- https://master.php.net/note/delete/86068
Reject -- https://master.php.net/note/reject/86068
Search -- https://master.php.net/manage/user-notes.php