Skip to content

Instantly share code, notes, and snippets.

@OskarStark
Created September 3, 2014 07:20
Show Gist options
  • Save OskarStark/c0c9e69fb70bd5a4b24e to your computer and use it in GitHub Desktop.
Save OskarStark/c0c9e69fb70bd5a4b24e to your computer and use it in GitHub Desktop.
<?php
/**
* Base version of the method
* @see http://www.php.net/manual/de/function.vsprintf.php#110666
*
* Like vsprintf, but accepts $args keys instead of order index.
* Both numeric and strings matching /[a-zA-Z0-9_-]+/ are allowed.
*
* @example: vskprintf('y = %y$d, x = %x$1.1f, key = %key$s', array('x' => 1, 'y' => 2, 'key' => 'MyKey'))
* Result: 'y = 2, x = 1.0'
*
* '%s' without argument name works fine too. Everything vsprintf() can do
* is supported.
*
* @author Josef Kufner <jkufner(at)gmail.com>
* @author Oskar Stark <oskar.stark@exozet.com>
*/
private function vksprintf($str, array $args)
{
if(empty($args)) {
return $str;
}
$map = array_flip(array_keys($args));
$new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/', function($m) use ($map) {
if(isset($map[$m[2]])) {
return $m[1] . '%' . ($map[$m[2]] + 1) . '$';
} else {
/*
* HACK!
* vsprintf all time removes '% and the following character'
*
* so we add 6 x # to the string.
* vsprintf will remove '%#' and later we remove the rest #
*/
return $m[1] . '%######' . $m[2][0] . '%' . $m[2] . '$';
}
},
$str);
$replaced_str = vsprintf($new_str, $args);
return str_replace('#####', '%', $replaced_str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment