2012-08-24 41 views
3

我想知道是否有評價像安全地評估簡單的數學

2+2 
10000+12000 
10000-20 
2 + 2 
40 - 20 + 23 - 12 

數學,而不必使用eval()因爲輸入可以來自任何用戶的可靠方法。我需要實現的只是整數的增加和減少。

是否有任何已存在的代碼片段,或者我沒有遇到的任何PHP函數?

+3

你可以先淨化輸入(如使用正則表達式,只允許數字和數學運算符) – bfavaretto

+0

您是否收到來自用戶輸入整個字符串? –

+0

@火箭是的我是 – Manhim

回答

4

我會質疑使用eval,綜合考慮各種數學函數在PHP可用。你說過你只想做簡單的數學運算 - 使用eval的唯一理由是執行更復雜的操作,或者接受來自用戶的整體布料。

如果你只是想增加或減少,消毒與intval輸入和去鎮:

$number1 = '100'; 
$number2 = 'shell_exec(\'rm -rf *\')'; 
echo intval($number1) + intval($number2); // 100 

試試:http://codepad.org/LSUDUw1M

這工作,因爲intval忽略任何非數字。

如果你確實是從用戶輸入(即100 - 20),你可以使用preg_replace刪除任何東西,除了允許運營商和數字讓整個方程式:

$input = '20 + 4; shell_exec(\'rm *\')'; 
$input = preg_replace(
    '/[^0-9+-]/', 
    '', 
    $input 
); 
eval('$result = '.$input.';'); 
echo 'result: '.$result; // 24 

試試:http://codepad.org/tnISDPJ3

這裏,我們使用正則表達式/[^0-9+-]/,它匹配任何NOT 0-9 OR + OR - 並將其替換爲空字符串。

如果你想獲得更多的深度與允許的方程,從eval手冊頁直取:

// credit for code to bohwaz (http://www.php.net/manual/en/function.eval.php#107377) 
$test = '2+3*pi'; 

// Remove whitespaces 
$test = preg_replace('/\s+/', '', $test); 

$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number 
$functions = '(?:abs|a?cosh?|a?sinh?|a?tanh?|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; 
} 

文檔

+1

我已經嚐到了我猜的eval的全部範圍。 – Manhim

3

你可以自己分析表達式。

事情是這樣的:

// Minus is the same as plus a negative 
// Also remove spaces after minus signs 
$str = preg_replace('/-\s*(\d+)/', '+-$1', $str); 

// Split on plusses 
$nums = explode('+', $str); 

// Trim values 
$nums = array_map('trim', $nums); 

// Add 'em up 
echo array_sum($nums); 

DEMO:http://codepad.org/ANc0gh27

+0

感謝您的好回答。 – Manhim

+0

我只是快速地將它們拼湊在一起,很高興它幫助:-) –

0

我用計算器腳本此方法。

$field1 = $_GET["field1"]; 
$field2 = $_GET["field2"]; 

$answer = $field1 + $field2; 
echo "$field1 + $field2 = $answer"; 
+0

這實際上並不真正工作,並沒有真正做我需要它做的事情。 – Manhim

+0

哦,但這工作正常,但不知道它是否在你的情況下不起作用..很抱歉...... – devWaleed

+0

它實際上是增加一個值相同的值,基本上做x + x = y。 – Manhim