vnsprintf is equal to vsprintf except for associative, signed or floating keys.
vnsprintf supports for example "%assocKey$05d", "%-2$'+10s" and "%3.2$05u", vsprintf doesn't
vnsprintf( '%2$d', $array) [2nd value] is equal to vsprintf( '%2$d', $array) [2nd value]
vnsprintf( '%+2$d', $array) [key = 2] is equal to vnsprintf( '%2.0$d', $array) [key = 2]
vnsprintf( '%+2$d', $array) [key = 2] is different of vsprintf( '%+2$d', $array) [unsupported]
When you use signed or floating keys, vnsprintf searchs for the signed truncated key of the original array
NoteĀ¹: vnsprintf does not support for example "%someKeyf" (floating number, key = someKey) or "%+03d" (signed decimal number, key = 3), you should use "%someKey$f" or "%+03$d" respectively.
NoteĀ²: "%+03d" (or "%1$+03d") will be interpreted as signed zero-padded decimal number
<?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) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
$len = strlen( $value[1][0]);
$format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
$offset -= $len - strlen( $key);
}
}
return vsprintf( $format, $data);
}
$examples = array(
2.8=>'positiveFloat', -3=>'negativeInteger', 'my_name'=>'someString' );
echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples); echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples); echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples); echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples); echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples); echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples); echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples); echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples); echo vsprintf( "%%2\$s = '%2\$s'\n", $examples); echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples); echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples); echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples); echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples); echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples); ?>