Created
July 25, 2020 15:59
-
-
Save AppleCEO/9d00070e075c7e538a5b80daf257db97 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* 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