Last active
January 1, 2016 13:49
-
-
Save goliatone/8153587 to your computer and use it in GitHub Desktop.
PHP string interpolation.
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 | |
class Message | |
{ | |
/** | |
* @param string $message String template | |
* @param array $context Context providing vars | |
* @param bool $consume If true, missing matches will be | |
* removed, else they are left. | |
* @return string | |
*/ | |
public static function interpolate($message, array $context = array(), $consume = FALSE) | |
{ | |
$getMatchReplace = function($match, $context) use($consume){ | |
$alt = $consume ? "" : "{".$match."}"; | |
$out = array_key_exists($match, $context) ? $context[$match] : $alt; | |
return is_callable($out) ? call_user_func($out, $match, $context) : $out; | |
}; | |
$replace = array(); | |
preg_match_all('/\{([^}]+)}/', $message, $matches); | |
foreach($matches[1] as $match) { | |
$match = trim($match); | |
$replace["{".$match."}"] = $getMatchReplace($match, $context); | |
} | |
//mb_strstr | |
return strtr($message, $replace); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment