Last active
February 15, 2022 13:42
-
-
Save MordiSacks/a67fc725ae1b9bc1d9844dd6583ad3f0 to your computer and use it in GitHub Desktop.
php template function
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 | |
function drop_vars(string $string, array $vars, array $enclosure = ['{{', '}}'], string $escapeStr = '@'): string | |
{ | |
// Escape escapeStr and enclosure | |
$escapeStr = preg_quote($escapeStr, '/'); | |
// Escape enclosure phrases | |
[$open, $close] = array_map(fn($i) => preg_quote($i, '/'), $enclosure); | |
// Search vars and replace with value | |
return preg_replace_callback("/($escapeStr?)($open\s?([^$open$close]*)\s*$close)/Uis", | |
function ($matches) use ($vars) { | |
[$original, $escape, $format, $var] = $matches; | |
// Check if escape return format | |
if (!empty($escape)) return $format; | |
// Trim spaces around var | |
$var = trim($var); | |
// Check if key exists in vars | |
if (array_key_exists($var, $vars)) return $vars[$var]; | |
return $format; | |
}, $string); | |
} | |
$str = <<<STR | |
Hi, My name is {{first_name}} | |
and my family name is {{ last_name}}, | |
To sum it up, my name is {{full_name }}. | |
I am a {{ job_title }}. | |
To use my function just write your vars like this @{{code}} | |
STR; | |
$vars = [ | |
'first_name' => 'John', | |
'last_name' => 'Doe', | |
'full_name' => 'John Doe', | |
'job_title' => 'Space Cowboy', | |
]; | |
echo drop_vars($str, $vars); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment