note 89349 added to function.vsprintf
| From: | jeppe dot dyrby at gmail dot com | Date: | Wed, 04 Mar 2009 12:52:45 +0000 |
| Subject: | note 89349 added to function.vsprintf | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151446@lists.php.net to get a copy of this message | ||
Heres a new version of the vnsprintf function, i call it dsprintf, but that should matter.
<?php
function dsprintf() {
$data = func_get_args(); // get all the arguments
$string = array_shift($data); // the string is the first one
if (is_array(func_get_arg(1))) { // if the second one is an array, use that
$data = func_get_arg(1);
}
$used_keys = array();
// get the matches, and feed them to our function
$string = preg_replace('/\%\((.*?)\)(.)/e',
'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string);
$data = array_diff_key($data,$used_keys); // diff the data with the used_keys
return vsprintf($string,$data); // yeah!
}
function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
if (isset($data[$m1])) { // if the key is there
$str = $data[$m1];
$used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
} else {
return "%".$m2; // else, return a regular %s, or %d or whatever is used
}
}
$str = "Hello, %(place)s, how is it hanning at %(place)s? %s works just as well";
$find = array(
'place' => 'world',
'sprintf',
'not used'
);
echo dsprintf($str, $find);
// 'Hello, world, how is it hanning at world? sprintf works just as well'
?>
----
Server IP: 87.54.44.10
Probable Submitter: 80.166.222.82
----
Manual Page -- http://www.php.net/manual/en/function.vsprintf.php
Edit -- https://master.php.net/note/edit/89349
Del: integrated -- https://master.php.net/note/delete/89349/integrated
Del: useless -- https://master.php.net/note/delete/89349/useless
Del: bad code -- https://master.php.net/note/delete/89349/bad+code
Del: spam -- https://master.php.net/note/delete/89349/spam
Del: non-english -- https://master.php.net/note/delete/89349/non-english
Del: in docs -- https://master.php.net/note/delete/89349/in+docs
Del: other reasons-- https://master.php.net/note/delete/89349
Reject -- https://master.php.net/note/reject/89349
Search -- https://master.php.net/manage/user-notes.php