Last active
December 11, 2015 23:08
-
-
Save pjdietz/4674235 to your computer and use it in GitHub Desktop.
Merge an associative array into a string template.
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 | |
/** | |
* 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