Reputation: 16055
I wanted to ask whether I'm doomed to use eval()
or there may be a work around.
$str = 'Hello, $user.'; // $str is a string gotten from an external source
// Many lines later
$user = 'John Doe';
echo eval('return "'.$str.'";');
Not a big fan of eval
, as probably many of you. Is there another way to parse a PHP string?
Upvotes: 0
Views: 122
Reputation: 152266
You can try with:
$str = 'Hello, $user.';
$data = array(
'user' => 'John Doe'
);
$output = preg_replace_callback('/\$(\w+)/', function($key) use ($data) {
return isset($data[$key[1]]) ? $data[$key[1]] : $key[1];
}, $str);
var_dump($output);
Output:
string 'Hello, John Doe.' (length=16)
Upvotes: 4
Reputation: 116140
You can try create_function
. It doesn't execute just any piece of code, but wraps it in a function. Apart from that, it's not that different.
But if your goal is to replace variables alone, you might want to have a look at the str_replace
function. That will work fine for a fixed set of variables. If you want to be more flexible, you can use preg_replace
or preg_replace_callback
, but note that a 'flexible' function is probably a function that allows you to use any variable. That also allows people to exploit that feature to read variables that they are not supposed to read.
Upvotes: 2