Friday 15 August 2014

php - Is string a math expression? -


How can I find out if the string is a math expression or not?

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

For example:

  "1 + 1" = & Gt; Right "2/2" = & gt; Truth "Hello" => Wrong "1 * 2 - X" = & gt; Wrong "m + u" = & gt; FALSE  
  class MathExpression {private static $ parentheses_open = array ('(', '{', '[']; personal Fixed $ parentheses_close = array (')', '}', ']'); Protected static function getParenthesesType ($ c) {if (in_array ($ c, MathExpression :: $ parentheses_open)) {return array_search ($ c, MathExpression :: $ parentheses_open)}} Otherwise (in_array ($ c, MathExpression :: $ parentheses_close)) {return array_search ($ c, MathExpression :: $ parentheses_close);} Other {return false;}} Public static work valid ($ expression ) {$ Size = strlen ($ expression); $ Tmp = array (); ($ I = 0; $ i & lt; $ size; $ i ++) {if (in_array ($ expression [$ i], methexpress:: $ $ $ $ parentheses_open} {$ tmp [] = $ expression [$ i];} otherwise (in_array ($ expression [$ i], MathExpression :: $ parentheses_close) {if (count ($ tmp) == 0) {return false;} If (Mathieu Expression :: ReceivedPrenetheusType (array_pop ($ TMP)) = Math-Expression :: Millenestentes Type ($ expression [$ i])) {return false; }}} If (count ($ tmp) == 0) {back true; } Other {return false; }} =} $ Test = array ('A1 + A2 * A3) + A5 + (B3 ^ B5) * (C1 * ((A3 / C2) + (B2 + C1)) to validate Mathematical expression for ',' (A1 + A2 * A3) + A5) * C1 + (B3 ^ B5 * (C1 * (A3 / C2) + (B2 + C1) ) ',' (A1 + A2 * A3) + A5 + (B2 + C1)) ',' (A1 + A2 * A3) + A5 + (B3 ^ B 5) * (C1 * (A3 / C2) + (B2 + C1)) '); // Testing in progress ... foreach ($ test trial) {$ isValid = MathExpression :: validate ($ test); Test of 'echo': '. $ Test '& Lt; Br> & # 39; & # 39; Var_dump (if $ is); }  

You can also examine and read the solution in detail

Also see For example, you can do this:

  $ result = INF; Try {Eval ("$ result =" + myMathExpression); // evaluate here) hold (exception $ e) {} if ($ result! = INF) echo ("expression is a valid mathematical expression.");  

Read more about this


No comments:

Post a Comment