我已经以下代码: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