使用eval从字符串计算数学表达式 [英] calculate math expression from a string using eval

查看:132
本文介绍了使用eval从字符串计算数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中计算数学表达式.我读过解决方案是使用eval().但是,当我尝试运行以下代码时:

I want to calculate math expression from a string. I have read that the solution to this is to use eval(). But when I try to run the following code:

<?php

$ma ="2+10";
$p = eval($ma);
print $p;

?>

它给了我以下错误:

解析错误:语法错误,意外出现$ end C:\ xampp \ htdocs \ eclipseWorkspaceWebDev \ MandatoryHandinSite \ tester.php(4) :第1行上的eval()代码

Parse error: syntax error, unexpected $end in C:\xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4) : eval()'d code on line 1

有人知道解决这个问题的方法吗?

Does someone know the solution to this problem.

推荐答案

虽然我不建议为此使用eval(这是 not 解决方案),但问题是需要完整的代码行,而不仅仅是片段.

While I don't suggest using eval for this (it is not the solution), the problem is that eval expects complete lines of code, not just fragments.

$ma ="2+10";
$p = eval('return '.$ma.';');
print $p;

应该做你想做的事.

更好的解决方案是为您的数学表达式编写一个分词器/解析器.这是一个非常简单的基于正则表达式的例子,

A better solution would be to write a tokenizer/parser for your math expression. Here's a very simple regex-based one to give you an example:

$ma = "2+10";

if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE){
    $operator = $matches[2];

    switch($operator){
        case '+':
            $p = $matches[1] + $matches[3];
            break;
        case '-':
            $p = $matches[1] - $matches[3];
            break;
        case '*':
            $p = $matches[1] * $matches[3];
            break;
        case '/':
            $p = $matches[1] / $matches[3];
            break;
    }

    echo $p;
}

这篇关于使用eval从字符串计算数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆