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
2010-02-17 00:42:32
preg_match('/-?\d+(\.\d+)*\h*[-+x\/]-?\d+(\.\d+)*/', $input); will catch negative numbers too.
wheresrhys
2010-02-17 00:56:07
@wheresrhys: thx, added to answer
soulmerge
2010-02-17 01:34:16
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
2010-02-17 00:43:33
Probably want more structure than that. That regex would match things like `"+09 ++"`, which is obviously not a sum.
Tim Yates
2010-02-17 00:45:16
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
2010-02-17 00:51:57