Patrick
Patrick

Reputation: 909

preg_replace - random word in array

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!

Upvotes: 1

Views: 570

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318508

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.

Upvotes: 2

Related Questions