我已經以下代碼:PHP EVAL解析錯誤
<?php
function calculate_string($mathString) {
$mathString = trim($mathString); // trim white spaces
$mathString = preg_replace("/[^0-9\(\)\+\-\*\/\.]/", "", $mathString);
return eval("return $mathString;");
}
$string1 = " (1 + 1) *3+ (2 + 2)";
echo calculate_string($string1);
$string2 = " (1 + 1) *3+* (2 + 2)";
echo calculate_string($string2);
?>
功能calculate_string()必須計算串給出一個PARAM數學表達式。首先調用string1工作良好。
但是,我如何檢測數學。字符串有數學。語法錯誤,如seconda調用, 並返回一些值取決於錯誤類型,或簡單地返回什麼(更好的解決方案)? 因此,當數學表達式在語法中包含錯誤時,第二個調用中的問題是parse_error。
請幫忙。
爲什麼你在正則表達式中有所有這些逃脫? 'preg_replace('〜[^ 0-9()* /。+ - ]〜','',$ mathString)'*完全等價於你現在擁有的東西,但更具可讀性。 – NullUserException
你應該看看使用語法高亮文本編輯器,如Notepad ++或JEdit,將幫助你捕捉解析錯誤,因爲它會打破語法高亮在錯誤的源頭。 –
*「如何檢測數學,字符串是否有數學錯誤,語法錯誤」*編寫適當的解析器,而不是使用'eval()'。 – NullUserException