Skip to content

Instantly share code, notes, and snippets.

@goliatone
Last active January 1, 2016 13:49
Show Gist options
  • Save goliatone/8153587 to your computer and use it in GitHub Desktop.
Save goliatone/8153587 to your computer and use it in GitHub Desktop.
PHP string interpolation.
<?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