Last active
May 11, 2016 07:27
-
-
Save Langmans/37f54e79a9c91e055ee6 to your computer and use it in GitHub Desktop.
format string %key% => array('key'=>'bla');
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
<?php | |
/** | |
* @param string $string | |
* @param array $replacements | |
* @param string $begin | |
* | |
* @return string | |
* | |
* @example "string_format_example.php" | |
*/ | |
function string_format($string, array $replacements = array(), $begin = '%'){ | |
$reverse_chars = array('(' => ')', '[' => ']', '{' => '}', '<' => '>'); | |
$end = strtr(strrev($begin), array_merge($reverse_chars, array_flip($reverse_chars))); | |
$replacements = array_combine(array_map(function ($key) use ($begin, $end) { | |
return $begin . $key . $end; | |
}, array_keys($replacements)), $replacements); | |
return strtr($string, $replacements); | |
} |
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
<?php | |
// output: Ruben said hello! | |
echo string_format("%person% said %greeting%!", array( | |
'person' =>'Ruben', | |
'greeting =>'hello' | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment