0

I have these codes:

$string = 'Hello [*tt();*], how are you today?';
preg_match("/\[\*(.*?)\*\]/",$string,$match);
$func = $match[1];
$d = eval($func);
$newstring = preg_replace("/\[\*(.*?)\*\]/",$d,$string);
echo $newstring;

function tt() {
     return 'test';
}

I think they reach my mean from them. I want to replace tt(); with its output.I expected it works but tt(); replace with nothing(null string).

hd.
  • 17,596
  • 46
  • 115
  • 165

3 Answers3

3

From the PHP documentation: http://au2.php.net/manual/en/function.eval.php

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned.

$d = eval("return $func");

eval should be used with caution. See When is eval evil in php?

Community
  • 1
  • 1
Jacob
  • 8,278
  • 1
  • 23
  • 29
  • wow,thank you.why is eval bad? because it can run a text as php code? I think using eval is bad when the text is getting from user.but in my case the text is define by admin directly in database. – hd. Feb 15 '11 at 07:10
  • Updated my answer, to be more informative than "eval is bad" :D – Jacob Feb 15 '11 at 07:19
1

$d = eval($func);

should be

eval('$d = ' . $func);

regality
  • 6,496
  • 6
  • 29
  • 26
1

Your regular expressions are fine. Your problem is with the eval() statement. It does not return a value like you expect. The assignment needs to happen in the eval() as well.

function tt() {
     return 'test';
}

$string = 'Hello [*tt();*], how are you today?';
preg_match("/\[\*(.*?)\*\]/",$string,$match);
$func = $match[1];
eval('$d = ' . $func);
$newstring = preg_replace("/\[\*(.*?)\*\]/",$d,$string);
echo $newstring;
Sander Marechal
  • 22,978
  • 13
  • 65
  • 96