-3

How can I found if string is a math expression or not?

It is enough to understand basic math expressions +, -, x, /

For Example:

"1+1" => TRUE

"2 / 2" => TRUE

"hello" => FALSE

"1 * 2 - X" => FALSE

"me + u" => FALSE
Farid Movsumov
  • 12,350
  • 8
  • 71
  • 97

3 Answers3

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);
}

you can check and read in detail about the solution here Is there possible to check mathematical expression string?

See also eval. For example, you can do this:

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

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

read more about it there

Community
  • 1
  • 1
Tashen Jazbi
  • 1,068
  • 1
  • 16
  • 41
  • **Woah there!** From the [PHP manual page for `eval()`](http://php.net/eval): "The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand." – esqew Mar 17 '15 at 19:19
  • @esqew yes it is, that's why i put it on the second option. you may go with first one :) – Tashen Jazbi Mar 17 '15 at 19:33
0

An extremely simple solution: Regex number,whitespace,[+,/,*,-,=],whitespace,Substring(recursion here) will work for any sequence of 1 + 1 + 2 + ... + 1 = 2 + 3 + 4 = 1 * 4 ... etc.

Obviously would not check if an expression is legit.

As per request, pseudo code:

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
  • 26
  • 4
-1

Maybe a regex with a pattern like this :

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