我必須建立一個計算一些數據的應用程序。我不知道科學家可以問什麼計算。如何評估算術計算?
例如, 用戶A將要計算(A + 5)* 3 用戶B將要計算(A + 14)²* PI
的算術公式由科學家定義並存儲在數據庫由管理員。
最簡單的方法就是做:
<?php
//Formula is initialized by a query in database
$formula= '(A + 3) * 5';
//$ value is an integer entered by UserA and verify by Controller
$value = 42;
$arithmetic = str_replace('A', $formula, $value);
$result = eval($arithmetic);
但因爲它是由@thpl在此answer
解釋評估和演示是邪惡的,我有兩個選擇:
- 要做好很多分析和轉換公式的每個字符和 創建一個很好的計算類。 (發現 一個
+
和替換+
字符的每個側面的操作通過調用addition
法等 等 - 檢查
$formula
具有良好的(是否安全?)正則表達式,並調用邪惡eval
功能。
第一個解決方案似乎更安全,但很長的發展
對於第二個方案,我發現這對PHP文檔:
<?php
$test = '2+3*pi';
// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);
$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^((' . $number . '|' . $functions . '\s*\((?1)+\)|\((?1)+\))(?:' . $operators . '(?2))?)+$/'; // Final regexp, heavily using recursive patterns
if (preg_match($regexp, $q)) {
$test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
eval('$result = ' . $test . ';');
} else {
$result = false;
}
第一個問題:第二個解決方案是否足夠安全?
我在互聯網上搜索(當然),但找到的最好的解決方案是以前的代碼。有一些PHP函數,珍珠或PECL庫來幫助我嗎?一個arithmetic_eval
函數?
(我不Security.SE問,因爲我的問題只涉及PHP)