tags:

views:

54

answers:

2

I have a form where the user can type something and I want my script to check if it's a sum (e.g. 5 x 5 or 3+ 3) how would I do this? Presumably using Regular Expressions?

+4  A: 

If you mean an "arithmetic operation", it would be something like (including floating point numbers)

preg_match('/-?\d+(\.\d+)?\h*[-+x\/]\h*-?\d+(\.\d+)?/', $input);
soulmerge
preg_match('/-?\d+(\.\d+)*\h*[-+x\/]-?\d+(\.\d+)*/', $input); will catch negative numbers too.
wheresrhys
@wheresrhys: thx, added to answer
soulmerge
A: 

You are talking about checking that this is a sum, but you are writting a product! If you want to check a sum, then accept only numbers and "+" sign :

preg_match('/^[ +0-9]+$/', $expression);
Aif
Probably want more structure than that. That regex would match things like `"+09 ++"`, which is obviously not a sum.
Tim Yates
true, but I think he might use a kind of parser to evaluate his expression, so it was just a very small test.But soulmerge answer is much better :-)
Aif