Posted By

ourlaputa on 09/04/13


Tagged

String formatted printf vsprintf


Versions (?)

Named specifier in php formatted strings, similar to Python's formatted strings using dictionaries


 / Published in: PHP
 

URL: http://stackoverflow.com/questions/7435233/name-php-specifiers-in-printf-strings

Taken from stackoverflow answer by user Jon

To test $foo = array('age' => 5, 'name' => 'john'); echo vsprintf_named("%(name)s is %(age)02d", $foo);

  1. function vsprintf_named($format, $args) {
  2. $names = preg_match_all('/%\((.*?)\)/', $format, $matches, PREG_SET_ORDER);
  3.  
  4. $values = array();
  5. foreach($matches as $match) {
  6. $values[] = $args[$match[1]];
  7. }
  8.  
  9. $format = preg_replace('/%\((.*?)\)/', '%', $format);
  10. return vsprintf($format, $values);
  11. }

Report this snippet  

You need to login to post a comment.