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?

2
  • $str = "" . (23 + $val); Sep 16, 2014 at 15:20
  • 23 is in the $str togheter with $val :( Sep 17, 2014 at 16:25

4 Answers 4

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;

?

1
  • Because 23 is inside $str :( Sep 17, 2014 at 16:23
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.

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.