1

I have this regular expression:

if(preg_match("/^(\\d+)(,)(\\d+)$/") ) { ... }

which tests that the user has entered a pair of numbers separated by a comma (e.g. 120,80). I've got that part working properly. However I anticipate that users may accidentally enter white space between any of the characters. I would like to make the expression ignore ALL white space characters, no matter where they occur in the pattern. I've tried this:

if(preg_match("/x^(\\d+)(,)(\\d+)$/x") ) { ... }

And also this:

if(preg_match("/(^(\\d+)(,)(\\d+))$/x") ) { ... }

But nothing seems to work. Any insights would be greatly appreciated. BTW I'm still learning this stuff so take that into account! Thanks. :D

codaddict
  • 445,704
  • 82
  • 492
  • 529
orbit82
  • 513
  • 3
  • 6
  • 17

2 Answers2

3

You might just strip whitespace before you do your regex match.

$input = str_replace(" ", "", $input);
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
2

Try:

if(preg_match("/^\s*\d+\s*,\s*\d+\s*$/",$input) ) { 
   // $input has two numbers separated by a comma and may have whitespace
   // around the number and/or around the comma.
}
codaddict
  • 445,704
  • 82
  • 492
  • 529