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

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

只是想找出正确和安全的方式来执行作为字符串传递的数学运算。在我的场景中,它是从图像EXIF数据中获取的值。

经过小小的研究,我找到了两种方法。

首先,使用eval:

function calculator1($str){
    eval("\$str = $str;");
    return $str;}

第二,使用create_function:

function calculator2($str){
    $fn = create_function("", "return ({$str});" );
    return $fn();};

这两个示例都需要字符串清理以避免恶意代码执行。有没有其他或更短的方法来做到这一点?


喵喔喔
浏览 1153回答 2
2回答

Qyouu

我做了这个: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;关于公式它必须至少包含两个操作数和一个运算符。操作数的名称可以是大写的,也可以是小写的。到目前为止,数学函数是sin,cos,pow…。不包括在内。我正在努力把它们包括进去。如果公式无效,则会收到如下错误消息:错误,您的公式(单变量)无效。参数的值必须是数值。
打开App,查看更多内容
随时随地看视频慕课网APP