dqdmvg7332 2016-09-28 10:14
浏览 43

如何评价数学公式由字符串组成? [重复]

This question already has an answer here:

In mm project i want to evaluate mathematical formula which is a string. Example: "((1*10)/100) + 100".

How can evaluate such formula? I used eval() but it is throwing Parse error: syntax error, unexpected end of file error and eval is not a safe function to use.

Is that anyway if i can do that? And if there is no way except eval then how should i do it? Why it thrown Parse error: syntax error, unexpected end of file error?

</div>
  • 写回答

2条回答 默认 最新

  • doudang8824 2016-09-28 10:24
    关注

    php's exec() function allows to execute commands, not to compute the result of a mathematical equation or formula. That is something completely different. That string does not contain any commands, so it is not valid syntax.

    Instead you need to feed a valid command into your call to exec() instead of a mathematical formula:

    Have a look at this simple example:

    <?php
    $input = '((1*10)/100) + 100';
    echo exec('php -r "echo ' . $input . ';"');
    

    This obviously requires a command line version of php being available as php in case you try to trigger that from within a http server. But the same certainly can be done using any other available interpreter, for example bash.

    An "inline" alternative (so without forking an external process) is to use php's eval() function. But again you need to feed it a command, not a formula. The advantage is that you do not have to rely on any other tool or interpreter to be usable at run time. The corresponding example would be:

    <?php
    $input = '((1*10)/100) + 100';
    echo eval('return ' . $input . ';');
    

    The output of both snippets obviously is 100.1.

    Note however that it is crucial for both approaches to have complete control over what formula you feed into the execution. Do not allow client side input to pass into this unfiltered! That would allow any attacker to execute arbitrary code on your system!

    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面