【问题标题】:Is string a math expression?字符串是数学表达式吗?
【发布时间】:2015-03-17 18:00:46
【问题描述】:

如何判断字符串是否为数学表达式?

了解基本的数学表达式+、-、x、/就足够了

例如:

"1+1" => TRUE

"2 / 2" => TRUE

"hello" => FALSE

"1 * 2 - X" => FALSE

"me + u" => FALSE

【问题讨论】:

标签: php math


【解决方案1】:
class MathExpression {

    private static $parentheses_open = array('(', '{', '[');
    private static $parentheses_close = array(')', '}', ']');

    protected static function getParenthesesType( $c ) {
        if(in_array($c,MathExpression::$parentheses_open)) {
            return array_search($c, MathExpression::$parentheses_open);
        } elseif(in_array($c,MathExpression::$parentheses_close)) {
            return array_search($c, MathExpression::$parentheses_close);
        } else {
            return false;
        }
    }

    public static function validate( $expression ) {
        $size = strlen( $expression );
        $tmp = array();
        for ($i=0; $i<$size; $i++) {
            if(in_array($expression[$i],MathExpression::$parentheses_open)) {
                $tmp[] = $expression[$i];
            } elseif(in_array($expression[$i],MathExpression::$parentheses_close)) {
                if (count($tmp) == 0 ) {
                    return false;
                }
                if(MathExpression::getParenthesesType(array_pop($tmp)) 
                    != MathExpression::getParenthesesType($expression[$i])) {
                    return false;
                }
            }
        }
        if (count($tmp) == 0 ) {
            return true;
        } else {
            return false;
        }
    }
}

//Mathematical expressions to validate
$tests = array(
    '(A1+A2*A3)+A5+(B3^B5)*(C1*((A3/C2)+(B2+C1)))',
    '(A1+A2*A3)+A5)*C1+(B3^B5*(C1*((A3/C2)+(B2+C1)))',
    '(A1+A2*A3)+A5++(B2+C1)))',
    '(A1+A2*A3)+A5+(B3^B5)*(C1*(A3/C2)+(B2+C1))'
);

// running the tests...
foreach($tests as $test) {
    $isValid = MathExpression::validate( $test );
    echo 'test of: '. $test .'<br>';
    var_dump($isValid);
}

你可以在这里Is there possible to check mathematical expression string?查看和阅读解决方案的详细信息

另见eval。例如,您可以这样做:

$result = INF;
try { 
  eval("$result=" + myMathExpression);  // Evaluate here
} catch (Exception $e) { 

} 
if($result != INF) echo("Expression is a valid mathematical expression.");

阅读更多信息there

【讨论】:

  • 哇!来自PHP manual page for eval():“eval() 语言结构非常危险,因为它允许执行任意 PHP 代码。因此不鼓励使用它。如果您已仔细验证除了使用此构造之外别无选择,请特别注意不要将任何用户提供的数据传入其中,而无需事先正确验证。”
  • @esqew 是的,这就是为什么我把它放在第二个选项上。你可以选择第一个:)
【解决方案2】:

一个极其简单的解决方案: 正则表达式数字、空格、[+、/、*、-、=]、空格、子字符串(这里递归) 将适用于任何序列 1 + 1 + 2 + ... + 1 = 2 + 3 + 4 = 1 * 4 ... 等等

显然不会检查表达式是否合法。

根据要求,伪代码:

if  Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)(\s*)([+,/,*,-,=])(\s*)))
    if (recursion())
         return True;
    else
         return False;
else //checking for end point
    if Regex(^(([0-9]+)(\s*)([+,/,*,-,=])(\s*)([0-9]+)))
         return True;
    else
         return False;

【讨论】:

  • 这只是一个很好的答案。 @Serj,你能提供实际的正则表达式吗?
  • 这不是为了我的享受,而是为了SO上的答案质量。为您的努力收回反对票。
【解决方案3】:

也许是一个具有这样模式的正则表达式:

^([-+/*]\d+(\.\d+)?)*

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 2015-12-12
    • 1970-01-01
    • 2018-05-19
    • 2011-05-09
    • 2012-05-29
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多