Skip to content

Instantly share code, notes, and snippets.

@Langmans
Last active May 11, 2016 07:27
Show Gist options
  • Save Langmans/37f54e79a9c91e055ee6 to your computer and use it in GitHub Desktop.
Save Langmans/37f54e79a9c91e055ee6 to your computer and use it in GitHub Desktop.
format string %key% => array('key'=>'bla');
<?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);
}
<?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