为了账号安全,请及时绑定邮箱和手机立即绑定

如何计算PHP中作为字符串传递的公式?

如何计算PHP中作为字符串传递的公式?

喵喔喔 2019-07-10 16:51:33
如何计算PHP中作为字符串传递的公式?只是想找出正确和安全的方式来执行作为字符串传递的数学运算。在我的场景中,它是从图像EXIF数据中获取的值。经过小小的研究,我找到了两种方法。首先,使用eval:function calculator1($str){     eval("\$str = $str;");     return $str;}第二,使用create_function:function calculator2($str){     $fn = create_function("", "return ({$str});" );     return $fn();};这两个示例都需要字符串清理以避免恶意代码执行。有没有其他或更短的方法来做到这一点?
查看完整描述

2 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

我做了这个:PHP公式解释器

它是怎么工作的?

首先,创建一个FormulaInterpreter公式及其参数

$formulaInterpreter = new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]);

使用execute()方法对公式进行解释。它将返回结果:

echo $formulaInterpreter->execute();

单行

echo (new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]))->execute();

实例

# Formula: speed = distance / time$speed = (new FormulaInterpreter("distance/time", ["distance" => 338, "time" => 5]))->e
xecute() ;echo $speed;#Venezuela night overtime (ordinary_work_day in hours): (normal_salary * days_in_a_work_month)/ordinary_work
_day$parameters = ["normal_salary" => 21000, "days_in_a_work_month" => 30, "ordinary_work_day" => 8];$venezuelaLOTTTArt118NightOvertime = (
new FormulaInterpreter("(normal_salary/days_in_a_work_month)/ordinary_work_day", $parameters))->execute();echo $venezuelaLOTTTArt118Nig
htOvertime;#cicle area$cicleArea = (new FormulaInterpreter("3.1416*(radio*radio)", ["radio" => 10]))->execute();echo $cicleArea;

关于公式

  1. 它必须至少包含两个操作数和一个运算符。
  2. 操作数的名称可以是大写的,也可以是小写的。
  3. 到目前为止,数学函数是sin,cos,pow…。不包括在内。我正在努力把它们包括进去。
  4. 如果公式无效,则会收到如下错误消息:

    错误,您的公式(单变量)无效。

  5. 参数的值必须是数值。


查看完整回答
反对 回复 2019-07-10
  • 2 回答
  • 0 关注
  • 1159 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信