简体   繁体   English

在php字符串中执行计算

[英]Perform calculation inside php string

I have a string like 我有一个像

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

Now, if I wanted to perform this calculation giving %%val%% a value, eg 20, how could I do? 现在,如果我要执行此计算,并为%%val%%一个值,例如20,该怎么办?

You can't. 你不能 PHP isn't recursively executable, unless you use eval() ( DON'T use eval() ). PHP不能递归执行,除非您使用eval()不要使用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. 这将回显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. 由于php不是强类型的,因此似乎很浪费,而且您可以轻松地将字符串转换为整数。

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() ) 但是请注意eval(请参阅: eval()

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. eval()语言构造非常危险,因为它允许执行任意PHP代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM