Created
November 12, 2017 00:41
-
-
Save andyexeter/2fa0b8783078e9417cf628c3ac6b86d0 to your computer and use it in GitHub Desktop.
Interpolates a handlebars style template with given data
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 a handlebars style template with the given data. | |
* | |
* e.g: interpolate('Hello, {{ name }}', ['name' => 'Joe Bloggs']); | |
* | |
* @param string $template | |
* @param array $data | |
* @return string mixed | |
*/ | |
function interpolate($template, $data) | |
{ | |
return preg_replace_callback('/{{\s*([^}\s]+)\s*}}/', function ($matches) use ($data) { | |
if (isset($data[$matches[1]])) { | |
return $data[$matches[1]]; | |
} | |
return $matches[0]; | |
}, $template); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment