我有3个变量和一个公式,可信的用户需要能够定义通过CMS。这个公式将随着时间的推移而变化,变量的值来自一个数据库。
我怎样才能算出这个计算的答案?我认为eval是相关的,但无法使它发挥作用。
$width = 10;
$height = 10;
$depth = 10;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace('W', $width, $volumetric);
$volumetric = str_replace('H', $height, $volumetric);
$volumetric = str_replace('D', $depth, $volumetric);
eval($volumetric);这给了我:
Parse error: parse error in /path/to/vol.php(13) : eval()'d code on line 1发布于 2016-07-28 12:15:52
您需要对eval非常小心,因为您允许用户直接在服务器上运行命令。确保彻底了解阅读文件并了解风险。
也就是说,您需要将结果赋值给一个变量。你也可以整理你正在做的事情,你只需要一个str_replace。试试这个:
$width = 10;
$height = 10;
$depth = 10;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace(['W', 'H', 'D'], [$width, $height, $depth], $volumetric);
eval("\$result = $volumetric;");
echo $result;发布于 2016-07-28 12:15:08
伊瓦尔是正确的方法..。我的正确代码是:
$width = 60;
$height = 60;
$depth = 60;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace('W', $width, $volumetric);
$volumetric = str_replace('H', $height, $volumetric);
$volumetric = str_replace('D', $depth, $volumetric);
eval('$result = '.$volumetric.';');
echo $result;发布于 2016-07-28 12:18:44
你的出发点是对的。如果您不想使用复杂的解析器或编写复杂的解析器,那么eval是最好的选择。但是,eval将给定的字符串转换为PHP代码。所以,基本上你所要做的就是;
$width = 10;
$height = 10;
$depth = 10;
$volumetric = '(W*H*D)/6000';
$volumetric = str_replace('W', $width, $volumetric);
$volumetric = str_replace('H', $height, $volumetric);
$volumetric = str_replace('D', $depth, $volumetric);
(10*10*10)/600;所以它输出错误。你应该把这个方程赋值给变量。正确的方法是;
eval('$result = ('.$volumetric.');');或
eval("\$result = ({$volumetric});")另外,我想补充一些东西。小心!在使用eval时。
https://stackoverflow.com/questions/38635842
复制相似问题