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!

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致