Skip to content

Instantly share code, notes, and snippets.

@andyexeter
Created November 12, 2017 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyexeter/2fa0b8783078e9417cf628c3ac6b86d0 to your computer and use it in GitHub Desktop.
Save andyexeter/2fa0b8783078e9417cf628c3ac6b86d0 to your computer and use it in GitHub Desktop.
Interpolates a handlebars style template with given data
<?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