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?
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?
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;
?
$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
$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.
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.