如何計算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個贊
它是怎么工作的?
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…。不包括在內。我正在努力把它們包括進去。 如果公式無效,則會收到如下錯誤消息: 錯誤,您的公式(單變量)無效。
參數的值必須是數值。
- 2 回答
- 0 關注
- 1237 瀏覽
添加回答
舉報
0/150
提交
取消