0

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?

6
  • If you not fan of eval() maybe sprintf() is an option? Commented Aug 21, 2014 at 8:44
  • 1
    str_replace('$user', $user, $str) ? Commented Aug 21, 2014 at 8:46
  • @FDL, wel that was just for the sake of the example. Obviously the variable will not always be $user Commented Aug 21, 2014 at 8:47
  • Will the replacements always be simple variables? How much PHP do you have to support in it? Commented Aug 21, 2014 at 8:47
  • @Barmar yes, but I was wondering if I could use php to parse it, instead of writing regular expressions, because, you know, the guys from PHP will certainly do it better than me Commented Aug 21, 2014 at 8:49

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I just did some benchmarking, with 1 replacement both eval and regex perform relatively equally fast, however if I add more variables eval becomes times faster. I guess I'll have to stick with it, unfortunately..
Well if I put an addslashes inside, since I have surrounding quotes, I guess it should be ok, no? eval('return "'.addslashes($str).'";');
2

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.

2 Comments

This function internally performs an eval() and as such has the same security issues as eval().
RegExes is the way, probably. Any other attempts will anyway lead to eval()` at sometime.

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.