Last active
August 29, 2015 13:56
-
-
Save bign8/9144510 to your computer and use it in GitHub Desktop.
Formatted Interpolate for PHP
This file contains 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 | |
/* | |
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