简体   繁体   中英

How to determine if a string is a Mathematical statement in PHP?

I have this string for an instance:

"2 + 2 - 2" and when evaluated it should return int(2) ;

I'm looking for a function/parser witch can determine if anykind of math content is matched within a string. More examples:

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

Do not need to evaluate and calculate these Math expressions, just need a function witch will determine ( True/False return values), if the statement is of this Math kind.

Is this possible with regex or something? Thanks!

Maybe run it as php on runtime and check that the responding value comes back as numeric. Take a look at this. http://php.net/manual/en/function.eval.php

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 evaluated!

If you know what type of expressions you will be parsing you could try to use regular expressions. Something like ^\\d+\\s*(\\+|-|\\*|\\\\)\\s*\\d+ should yield true if you are trying to validate the binary operators of + , * , - and \\ . So it would validate items such as 3 + 3 , 2 - 0 , etc.

You can use a parser generator from XP-framework. See sample grammar for calculator, which can be translated to PHP code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM