Skip to content

Instantly share code, notes, and snippets.

@insideone
Last active May 15, 2016 13:29
Show Gist options
  • Save insideone/26b3f15e1ed271bfd41a85a8098fb3f1 to your computer and use it in GitHub Desktop.
Save insideone/26b3f15e1ed271bfd41a85a8098fb3f1 to your computer and use it in GitHub Desktop.
PHP: uptemplate
<?php
echo untemplate('Привет, #WHO#!', array('WHO' => 'Мир')); // Привет, Мир!
<?php
/**
* @param string $template
* @param array $replacements
* @param array $settings Настройки. Заполняется настройками по-умолчанию по незаполненным ключам
* Делает из шаблона готовую строку заменяя макросы значениями из $replacements (ключ без style == макрос)
* Незамененные макросы заменяются на replace_default
*/
function untemplate($template, $replacements, $settings = array())
{
$default_settings = array('style' => '#', 'values_separator' => ', ', 'replace_default' => '');
$settings = array_merge($default_settings, $settings);
extract($settings);
if ( is_array($style) )
{
$begin_macro = $style[0];
$end_macro = $style[1];
}
else
{
$begin_macro = $end_macro = $style;
}
foreach($replacements as $key => $value)
{
$replacements["{$begin_macro}$key{$end_macro}"] = is_array($value) ? implode($values_separator, $value) : $value;
unset($replacements[$key]);
}
return preg_replace("~({$begin_macro}.+{$end_macro})~U", $replace_default, str_replace(array_keys($replacements), array_values($replacements), $template));
}
function untemplate4walk($template, $key, $replacements)
{
return untemplate($template, $replacements);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment