Skip to content

Instantly share code, notes, and snippets.

@bign8
Last active August 29, 2015 13:56
Show Gist options
  • Save bign8/9144510 to your computer and use it in GitHub Desktop.
Save bign8/9144510 to your computer and use it in GitHub Desktop.
Formatted Interpolate for PHP
<?php
/*
name: formatted interpolate (see: http://bit.ly/198oCOP on interpolation)
author: bign8
description: using the format "{key|format}", interpolatef does formatted interpolation of strings using sprintf formatting
*/
function interpolatef( $message, array $context = array()) {
$callback = function ($matches) use ($context) { // function that formats data as specified
$format = $matches[2] == '' ? '%s' : $matches[2] ; // default format
return (isset($context[$matches[1]])) ? sprintf($format, $context[$matches[1]]) : $matches[0];
};
return preg_replace_callback( '/{([^\|}]+)\|?([^}]*)}/', $callback, $message ); // replacement query
}
// sample use
$message = '${initial|%01.2f} for first {after|%d} attendee(s), ${later|%01.2f} for additional';
$context = array(
'initial' => 200,
'after' => 3,
'later' => 150
);
echo interpolatef( $message, $context ); // $200.00 for first 3 attendee(s), $150 for additional
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment