Skip to content

Instantly share code, notes, and snippets.

@codearachnid
Last active December 10, 2015 16:39
Show Gist options
  • Save codearachnid/4462713 to your computer and use it in GitHub Desktop.
Save codearachnid/4462713 to your computer and use it in GitHub Desktop.
vsprintf, sprintf, and printf do not allow for associative arrays to perform replacements `sprintf_assoc` resolves this by using the key of the array in the lookup for string replacement. http://php.net/manual/en/function.vsprintf.php
<?php
function sprintf_assoc( $string = '', $replacement_vars = array(), $prefix_character = '%' ) {
if ( ! $string ) return '';
if ( is_array( $replacement_vars ) && count( $replacement_vars ) > 0 ) {
foreach ( $replacement_vars as $key => $value ) {
$string = str_replace( $prefix_character . $key, $value, $string );
}
}
return $string;
}
function printf_assoc( $string = '', $replacement_vars = array(), $prefix_character = '%' ) {
echo sprintf_assoc( $string, $replacement_vars, $prefix_character );
}
echo sprintf_assoc( '%action_direction the sliced %object in lemon juice for %s.', array(
'action_direction' => 'Soak',
'object' => 'avocado',
'time' => '2 minutes'
) );
// Soak the sliced avocado in lemon juice for 2 minutes.
@slowkow
Copy link

slowkow commented Jul 15, 2015

This function is incorrect. You have not accounted for the %s in your string.

The output is:

Soak the sliced avocado in lemon juice for %s.

Notice that 2 minutes is not included in the string.

See here for a correct implementation of a similar function:

https://github.com/washingtonpost/datawrapper/blob/master/lib/utils/vksprintf.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment