0

I have a text file (math.txt) in which any kind of arithmetic operation could be written. I have to read the file using PHP and determine the output. I am using the below mentioned code to read the content of the file.

$file = 'math.txt';  // 2+3 is written in math.txt

$open = fopen($file, 'r');

$read = fgets($open);
$close = fclose($open);

Using the above code, i am getting the content. But echoing the content is displaying the original content (i.e 2+3) rather than displaying the output(i.e 5). I am not understanding what should i do in this case.

Any help on this will be appreciated. Thanks in advance.

4

2 回答 2

1

但是回显内容是显示原始内容(即2+3)而不是显示输出(即5)。

这是完全预期的行为。您从文件中读取了一个字符串。PHP 应该如何知道您希望它计算表达式?

您必须实现一个简单的解析器(或在 Internet 上搜索一个)来分析表达式并计算结果。

dave1010在他的一篇文章中提供了一个非常好的功能:

function do_maths($expression) {
  eval('$o = ' . preg_replace('/[^0-9\+\-\*\/\(\)\.]/', '', $expression) . ';');
  return $o;
}

echo do_maths('1+1');

但请注意,如果输入包含语法错误,这仍然会停止您的脚本执行!

这是一个使用真正解析器的更好的库:https ://github.com/stuartwakefield/php-math-parser

于 2013-08-11T14:13:16.883 回答
0

根据运算符读取文件解析

        like     file=2*5;
             $open = fopen($file, 'r');

              $read = fgets($open);


                $key = preg_split("/[*+-\/]+/", $read);

                 $operator= substr($a, strpos($a,$key[1])-1,1);


                 if($operator=='+')
                 {
                 echo $key[0]+ $key[1];
                 }
                 else  if($operator=='-')
                 {
                 echo $key[0]- $key[1];
                 }
                 else  if($operator=='*')
                 {
                 echo $key[0]* $key[1];
                 }
                 else  if($operator=='/')
                 {
                 echo $key[0]/$key[1];
                 }
于 2013-08-11T14:58:16.373 回答