bobsuncle
bobsuncle

Reputation: 1

Checking input is a sum in PHP

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?

Upvotes: 0

Views: 206

Answers (2)

soulmerge
soulmerge

Reputation: 75724

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);

Upvotes: 4

Aif
Aif

Reputation: 11220

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);

Upvotes: 0

Related Questions