0

I have an textbox, for user input an expression. I want to validate the inputed expression. Is there any way to do this?
For example : (1 * 2) + 3 *4 is True, (1 ** 2) +* 3 is false.
Thanks so much.

Himanshu
  • 4,327
  • 16
  • 31
  • 39

2 Answers2

0

AFAIK you're going to need to use eval(), unless you want to pull some shenanigans with php_check_syntax() which would require you to save the expression to a file, which seems unwieldy.

eval() will return false if there's a syntax error in the code; if not, it will return null or the return value of the supplied expression. This will cause you some grief if you're evaluating an expression that returns false normally, though.

Note that using eval() will allow anyone to input arbitrary PHP into your form and have it executed, which can obviously be a Very Bad Idea and should be approached with extreme caution.

Check out this similar question: PHP eval and capturing errors (as much as possible)

Community
  • 1
  • 1
beef_boolean
  • 147
  • 3
  • 3
0

I don't know if this will be of any help (your question is a bit vague*), but someone has a aritmethic evaluator (without eval!) available: PHP function to evaluate string like "2-1" as arithmetic 2-1=1

Then perhaps assign the results as

$true = <(1 * 2) + 3 *4 result here>;
$false = <(1 ** 2) +* 3 result here>;

and use for validating.

If you need to just validate the strings, try regular expressions or exact string matching with spaces removed.

// Basic string matching.
$expected = '(1*2)+3*4';
$data = <get data from text input to this variable or similar>;

if ($expected == str_replace(' ', '', $data)) {
    return true;
}

...

If you need to validate the formatting (e.g. mathematical correctness of the given string), try the arithmetic evaluator to check whether the string returns a number:

$value = <use arithmetic evaluator to get the value>;

if (is_numeric($value)) {
    return true;
}

...

* Could you make it clearer what in those values should return true or false. Does it need to be calculated to a certain number value? Does the string need to be an exact match? Does the string change constantly and need to be validated as a proper mathematically correct expression?

Community
  • 1
  • 1
ojrask
  • 2,799
  • 1
  • 23
  • 23