I have the following Code.
<?php
$user['username'] = 'Bastian';
$template = 'Hello {user:username}';
$template = preg_replace('/\{user\:([a-zA-Z0-9]+)\}/', $user['\1'], $template);
echo $template;
// Output:
// Notice: Undefined index: \1 in C:\xampp\htdocs\test.php on line 5
// Hello
I think, you know what i would do (i hope you know).
I try to replace $user[‘$1’], $user[“$1”] or $user[$1], Nothing Works!
I hope you can help my =)
Thank you in Advance!
You need to use
preg_replace_callback()– the replacement ofpreg_replace()is a string so you cannot use PHP code there. And no, the/emodifier is not a solution since eval is evil.Here’s an example (it requires PHP 5.3 but you should be using a recent version anyway!):
If you have to use an old PHP version, you could do it like this. It’s much uglier due to the use of a global variable though:
However, consider using a template engine such as h2o instead of implementing it on your own.