Created
June 1, 2015 09:24
-
-
Save wernerhp/c3d23d3dabd2143d6a41 to your computer and use it in GitHub Desktop.
Formats a string using an associative array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
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
Sweet ;)