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


/ Published in: PHP
Save to your folder(s)

Taken from stackoverflow answer by user Jon

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.