Skip to content

Instantly share code, notes, and snippets.

@AppleCEO
Created July 25, 2020 15:59
Show Gist options
  • Save AppleCEO/9d00070e075c7e538a5b80daf257db97 to your computer and use it in GitHub Desktop.
Save AppleCEO/9d00070e075c7e538a5b80daf257db97 to your computer and use it in GitHub Desktop.
<?php
/**
* Interpolates context values into the message placeholders.
*/
function interpolate($message, array $context = array())
{
// build a replacement array with braces around the context keys
$replace = array();
foreach ($context as $key => $val) {
// check that the value can be cast to string
if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
$replace['{' . $key . '}'] = $val;
}
}
// interpolate replacement values into the message and return
return strtr($message, $replace);
}
// a message with brace-delimited placeholder names
$message = "User {username} created";
// a context array of placeholder names => replacement values
$context = array('username' => 'bolivar');
// echoes "User bolivar created"
echo interpolate($message, $context);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment