note 65181 added to function.sprintf
| From: | egingell at sisna dot com | Date: | Wed, 26 Apr 2006 08:51:21 +0000 |
| Subject: | note 65181 added to function.sprintf | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-109732@lists.php.net to get a copy of this message | ||
<?
/**
* [string or int] vprint ( string $format [, mixed $ary [, bool $return]] )
*
* Closely mimics the functionality of sprintf(), printf(), vprintf(), and vsprintf().
*
* Replaces %[bcdeufFosxX] with each element of $ary
* See http://us3.php.net/manual/en/function.sprintf.php
for details on replacement types.
*
* If there are not enough elements in $ary (or it is left out) to satisfy $format,
* it will be padded to the correct length.
*
* Since v*printf() doesn't mind having too many elements in the array, $format will be left
alone.
*
* If $ary is a string, it will be recast into an array.
*
* If $return is set to a value considered to be false (0, '', null, false, and array()),
* then the output will be sent to STDOUT and the strlen() of the output string will be returned;
* otherwise, the output string will be returned.
*
* It's buggy when using the argument swapping functionality, unless you do it propperly.
*
* May break when using modifiers (%.4e, %02s, etc), unless you do it propperly.
**/
function vprint($format, $ary = array(), $return = true) {
// Sanity?!
if (!is_array($ary)) $ary = array($ary);
// Find %n$n.
preg_match_all('#\\%[\\d]*\\$[bcdeufFosxX]#', $format, $matches);
// Weed out the dupes and count how many there are.
$counts = count(array_unique($matches[0]));
// Count the number of %n's and add it to the number of %n$n's.
$countf = preg_match_all('#\\%[bcdeufFosxX]#', $format, $matches) + $counts;
// Count the number of replacements.
$counta = count($ary);
if ($countf > $counta) {
// Pad $ary if there's not enough elements.
$ary = array_pad($ary, $countf, " ");
}
if ($return) {
return vsprintf($format, $ary);
} else {
return vprintf($format, $ary);
}
}
?>
----
Server IP: 216.194.113.175
Probable Submitter: 65.100.194.45
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.sprintf.php
Edit -- http://master.php.net/note/edit/65181
Del: integrated -- http://master.php.net/note/delete/65181/integrated
Del: useless -- http://master.php.net/note/delete/65181/useless
Del: bad code -- http://master.php.net/note/delete/65181/bad+code
Del: spam -- http://master.php.net/note/delete/65181/spam
Del: non-english -- http://master.php.net/note/delete/65181/non-english
Del: in docs -- http://master.php.net/note/delete/65181/in+docs
Del: other reasons-- http://master.php.net/note/delete/65181
Reject -- http://master.php.net/note/reject/65181
Search -- http://master.php.net/manage/user-notes.php