1

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!

1 Answer 1

2

You need to use preg_replace_callback() - the replacement of preg_replace() is a string so you cannot use PHP code there. And no, the /e modifier 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!):

$user['username'] = 'FooBar';
$template = 'Hello {user:username}';
echo preg_replace_callback('/\{user\:([a-zA-Z0-9]+)\}/', function($m) use ($user) {
    return $user[$m[1]];
}, $template);

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:

function replace_user($m) {
    global $user;
    return $user[$m[1]];
}
echo preg_replace_callback('/\{user\:([a-zA-Z0-9]+)\}/', 'replace_user', $template);

However, consider using a template engine such as h2o instead of implementing it on your own.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much ^^ <?php $user['userID'] = '1'; $user['username'] = 'FooBar'; function repl($m) { global $user; return $user[$m[1]]; } $template = 'Hello <a href="index.php?userID={user:userID}">{user:username}</a>'; echo preg_replace_callback('/\{user\:([a-zA-Z0-9]+)\}/', 'repl', $template); // Output: // Hello <a href="index.php?userID=1">FooBar</a></code>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.