How to determine if a string is a mathematical expression in PHP?

I have this line for the instance:

"2 + 2 - 2" , and in evaluating it should return int(2) ;

I am looking for a function / parser that can determine if anykind matches the mathematical content in a string. Additional examples:

 "(2 + 2) / 2" "(4 / 8) * 12" "128 * 8" 

You do not need to evaluate and calculate these mathematical expressions, you just need a function that determines ( True/False return values) if the operator belongs to this type of mathematics.

Is this possible with regex or something else? Thanks!

+4
source share
4 answers

See 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."); 

Just be careful because any PHP code will be appreciated!

0
source

Perhaps run it as php at runtime and make sure the response value is returned as a number. Take a look at this. http://php.net/manual/en/function.eval.php

+1
source

If you know what types of expressions will be processed, you can try using regular expressions. Something like ^\d+\s*(\+|-|\*|\\)\s*\d+ should give true if you are trying to check the binary operators + , * , - and \ . This way it will check for elements like 3 + 3 , 2 - 0 , etc.

0
source

You can use the parser generator from the XP-framework. See a sample grammar for a calculator that can be translated into PHP code.

0
source

Source: https://habr.com/ru/post/1402914/


All Articles