【问题标题】:PHP eval parse error [closed]PHP eval解析错误[关闭]
【发布时间】:2012-11-28 20:29:53
【问题描述】:

我有以下代码:

<?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() 必须计算以字符串形式给出的数学表达式作为参数。第一次调用 string1 效果很好。

但是,我如何检测数学。字符串有数学。语法错误,例如在 seconda 调用中, 并返回一些值取决于错误类型,还是简单地不返回任何内容(更好的解决方案)? 因此,当数学表达式包含语法错误时,问题是第二次调用中的 parse_error。

请帮忙。

【问题讨论】:

  • 为什么你在正则表达式中有所有这些转义? preg_replace('~[^0-9()*/.+-]~', '', $mathString)完全等同于你现在拥有的,但更具可读性。
  • 您应该考虑使用像 Notepad++ 或 JEdit 这样的语法高亮文本编辑器,这将帮助您捕获解析错误,因为它会在错误源处破坏语法高亮。
  • “我如何检测 math.string 是否有 math.error in syntax” 编写一个合适的解析器而不是使用eval()

标签: php eval parse-error


【解决方案1】:

好的,所以你想在*3+* 中显示类似的内容:

$string2 = " (1 + 1) *3+* (2 + 2)";

您可以通过多种方式做到这一点,通过自己检查字符串是否有一些常见错误或检查eval() 的返回值 (docs):

从 PHP 7 开始,如果评估代码中存在解析错误,则 eval() 引发 ParseError 异常。在 PHP 7 之前,在本例中为 eval() 返回 FALSE 并正常继续执行以下代码。 无法在 eval() 中使用 set_error_handler().

【讨论】:

  • 您不能使用set_error_handler() 来捕获eval'd 代码中的错误。来源:the docs
  • 是的。已更正
猜你喜欢
  • 2010-11-18
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 2014-12-03
  • 2013-10-02
  • 1970-01-01
相关资源
最近更新 更多