Last active
May 15, 2016 13:29
-
-
Save insideone/26b3f15e1ed271bfd41a85a8098fb3f1 to your computer and use it in GitHub Desktop.
PHP: uptemplate
This file contains 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 | |
echo untemplate('Привет, #WHO#!', array('WHO' => 'Мир')); // Привет, Мир! |
This file contains 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 | |
/** | |
* @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