Search code examples
phpregexstringfloating-pointpreg-match

Regex fails with decimal digits (.00) causes preg_match() to return FALSE


I've got a prize input field in my form. Valid user input should always look like this:

1.00
0.00
10000.20
100.25

Before the floating point there could be unlimited digits, after only 2 digits. I tried to achieve this with that regex:

/^([0-9]+)\.([0-9]{2})$/

If you check this out here: https://regex101.com/ there is a match for the value 10.00.

But now in PHP I used preg_match() as follows:

!preg_match('/^([0-9]+)\.([0-9]{2})$/', $obj->getPrize());
  • 10.00 returns true
  • 10.01 returns false

Can anyone explain the difference? Why does 10.00 return true? I think preg_match() handles zeros differently, but how to achieve this task?


Solution

  • Your problem is not the regex. It's your numbers, because PHP just trims your 0's if you don't have any necessary numbers at the end. You can see this with this code:

    $num = 10.00;
    var_dump($num);
    
    $num = 10.01;
    var_dump($num);
    

    output:

    float(10)
    float(10.01)
    

    As you can see in the first output there is no .00 simply because you don't have any numbers after it. But your regex requiers 2 digits after . and that is why your regex fails.

    Now one solution can be just to make \.([0-9]{2}) optional, e.g.

    ^([0-9]+)(?:\.([0-9]{2}))?$