0

I have a string like

$str = "23 + %%val%%";

Now, if I wanted to perform this calculation giving %%val%% a value, e.g. 20, how could I do?

Dan
  • 9,391
  • 5
  • 41
  • 73

4 Answers4

1

You can't. PHP isn't recursively executable, unless you use eval() (DON'T use eval()). Why can't you just do

$str = 23 + $val;

?

Marc B
  • 356,200
  • 43
  • 426
  • 500
0
$a = 10;
$b = 10;
$c = 10;
$string = "a + b + c";

$result = eval('return ' . preg_replace('/([a-zA-Z0-9])+/', '\$$1', $string) . ';');
echo $result;

this will echo 30.

there is another post about this here Calculate a sum in a string

Community
  • 1
  • 1
Maantje
  • 104
  • 1
  • 1
  • 10
0
$str = "23 + {$value}"

Then to perform the calculation, you'd need a function that takes a string and breaks up the integers and operators. Seems like a waste since php is not strongly typed, and you can easily convert strings to integers.

J-Dizzle
  • 3,176
  • 6
  • 31
  • 49
0

If you really want to keep this format, you can do this :

function calculate($string, $value) {
  return str_replace('%%val%%', $value, $string);
}

$str = "23 + %%val%%";
$value = 25;
$result = eval('return '.calculate($str, $value).';');

var_dump($result); // int(48)

$result = eval('return '.calculate("16 + %%val%%", 10).';');

var_dump($result); // int(26)

But be careful with eval (See : eval())

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code.

fdehanne
  • 1,658
  • 1
  • 16
  • 32