- preg_replace_callback: documentation ( source)
- define: documentation ( source)
<?php
define('SITE_URL', 'http://example.com');
$vars = [
'SITE_URL' => SITE_URL
];
$template = '<p class="card mb-4 shadow-sm"><img src="{{ SITE_URL }}/assets/images/blog/php.png" alt="php" title="php"></p>';
// match any single word with _ or -, with spaces either side or not
// e.g: {{key}} or {{ key }} or {{key-foo}} or {{ key-foo }}
// not {{ a b c }}
$str = preg_replace_callback("/\{\{[ ]{0,}([\w\_-]{1,})[ ]{0,1}\}\}/", function ($match) use ($vars) {
return array_key_exists($match[1], $vars) ? $vars[$match[1]] : '';
}, $template);
echo $str;