Skip to content

Instantly share code, notes, and snippets.

@pjdietz
Last active December 11, 2015 23:08
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 pjdietz/4674235 to your computer and use it in GitHub Desktop.
Save pjdietz/4674235 to your computer and use it in GitHub Desktop.
Merge an associative array into a string template.
<?php
/**
* Merge an associative array into a string template.
*
* @param string $template
* @param array $mergeFields
* @return string
*/
function stringFromTemplate($template, $mergeFields)
{
return str_replace(
array_keys($mergeFields),
array_values($mergeFields),
$template);
}
// -----------------------------------------------------------------------------
// Example:
// Make a string to use as a template. Include markers to use to indicate where
// to insert the merged field values. I used curly braces and caps to make them
// stand out, but it makes no difference.
$template = <<<'HTML'
<div class="example">
<h1>{TITLE}</h1>
<div class="description">{DESCRIPTION}</div>
</div><!-- .example -->
HTML;
// Make an associative array using markers from the template string as keys
// and the strings you'd like to merge into the template as values.
$fields = array(
'{TITLE}' => 'My Title',
'{DESCRIPTION}' => '<p>Here’s some intersting stuff...</p>'
);
// Call the function.
$merged = stringFromTemplate($template, $fields);
print $merged;
/*
Outputs:
<div class="example">
<h1>My Title</h1>
<div class="description"><p>Here’s some intersting stuff...</p></div>
</div><!-- .example -->
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment