Skip to content

Instantly share code, notes, and snippets.

@wernerhp
Created June 1, 2015 09:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wernerhp/c3d23d3dabd2143d6a41 to your computer and use it in GitHub Desktop.
Save wernerhp/c3d23d3dabd2143d6a41 to your computer and use it in GitHub Desktop.
Formats a string using an associative array.
/**
* Formats a string using an associative array.
* Example:
* echo nsprintf(":name :surname is :age", array('name' => 'John', 'age' => '29', 'surname' => 'Doe'));
*
* @param string $format A formatted string with named template fields
* @param array $args An associative array of values to place in the formatted string.
* @return string A formatted string
*/
function nsprintf($format, $args)
{
$names = preg_match_all('/\:\S*\b/', $format, $matches, PREG_SET_ORDER);
$values = array();
foreach ($matches as $match) {
$values[] = $args[str_replace(':', '', $match[0])];
}
$format = preg_replace('/\:\S*\b/', '%s', $format);
return vsprintf($format, $values);
}
@jacqueswww
Copy link

Sweet ;)

@Cosmologist
Copy link

See my implementation - https://github.com/Cosmologist/Gears/blob/master/src/Gears/StringType.php#L115
You can specify another modificators (not %s only) and use more standard expression style - like 'test %(string)s'

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