0

I am trying to use preg_match to match numbers that start with a zero to indicate an invalid input. Numbers such as 01, 0023, 00.4 are invalid; however numbers such as 0.12 are valid. The input would be a calculator entry, such as 09 * 108 + 0.19 + 4009. In this case, the expression would be invalid because of the 09.

So far my expression looks like: preg_match("/[^1-9]+0[0-9]+/", $subject)

What I tried to do was match when a zero precedes any string of digits, but is also not preceded by another string of digits. So 109 is valid, but 1+09 is invalid. However it isn't working for cases like 1 + 4009.

noufalcep
  • 3,446
  • 15
  • 33
  • 51
mr_robot
  • 3
  • 3
  • 2
    Start with zero = `^0`. RegEx `^0\d+$`. Not starts with zero `^[^0]` – Tushar Oct 05 '16 at 03:11
  • 1
    Maybe `0\.\d+(*SKIP)(*FAIL)|\b0\d+`. – chris85 Oct 05 '16 at 03:57
  • Wow! Thanks @chris85, your answer works well. I've never seen the SKIP, FAIL expressions used before. Can you explain a bit about what they mean? – mr_robot Oct 05 '16 at 04:11
  • You can read more about them here, http://stackoverflow.com/questions/24534782/how-do-skip-or-f-work-on-regex and http://www.rexegg.com/regex-best-trick.html#pcrevariation. Looks like the answer below will work for you though. – chris85 Oct 05 '16 at 12:51

1 Answers1

1
preg_match('/\b0[0-9]+(?:\.[0-9]+)?\b/', $subject)

\b for word boundary.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138