note 87031 added to function.vsprintf
| From: | www dot wesley at gmail dot com | Date: | Sat, 15 Nov 2008 20:02:02 +0000 |
| Subject: | note 87031 added to function.vsprintf | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-146584@lists.php.net to get a copy of this message | ||
Here's the new version of vnsprintf()
Thanks to "César Kästli" and "Jan Ulrych"
<?php
function vnsprintf( $format, array $data)
{
preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2)
(?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format,
$match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
$offset = 0;
$keys = array_keys($data);
foreach( $match as &$value )
{
if ( ( $key = array_search( $value[1][0], $keys, TRUE) ) !== FALSE || ( is_numeric( $value[1][0] )
&& ( $key = array_search( (int)$value[1][0], $keys, TRUE) ) !== FALSE) )
{
$len = strlen( $value[1][0]);
$format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
$offset -= $len - strlen( 1 + $key);
}
}
return vsprintf( $format, $data);
}
$example = array(
0 => 'first',
'second' => 'second',
'third',
4.2 => 'fourth',
'fifth',
-6.7 => 'sixth',
'seventh',
'eighth',
'9' => 'ninth',
'tenth' => 'tenth',
'-11.3' => 'eleventh',
'twelfth'
);
echo vnsprintf( '%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s %10$s %11$s %12$s<br
/>', $example); // acts like vsprintf
echo vnsprintf( '%+0$s %second$s %+1$s %+4$s %+5$s %-6.5$s %+6$s %+7$s %+9$s %tenth$s %-11.3$s
%+10$s<br />', $example);
?>
----
Server IP: 200.185.126.110
Probable Submitter: 189.71.31.224
----
Manual Page -- http://www.php.net/manual/en/function.vsprintf.php
Edit -- https://master.php.net/note/edit/87031
Del: integrated -- https://master.php.net/note/delete/87031/integrated
Del: useless -- https://master.php.net/note/delete/87031/useless
Del: bad code -- https://master.php.net/note/delete/87031/bad+code
Del: spam -- https://master.php.net/note/delete/87031/spam
Del: non-english -- https://master.php.net/note/delete/87031/non-english
Del: in docs -- https://master.php.net/note/delete/87031/in+docs
Del: other reasons-- https://master.php.net/note/delete/87031
Reject -- https://master.php.net/note/reject/87031
Search -- https://master.php.net/manage/user-notes.php