php-src icon indicating copy to clipboard operation
php-src copied to clipboard

preg_match fails to match zero

Open Adam2Marsh opened this issue 4 years ago • 5 comments

Description

The following code:

<?php

$value=0.0;

preg_match("/(\d+)\.(\d+)/",$value, $matches);

print_r($matches);

Resulted in this output:

Array
(
)

But I expected this output instead:

Array
(
    [0] => 0.0
    [1] => 0
    [2] => 0
)

I found this as in my code I need to strip the numbers off the decimal point, now sometimes that decimal point might just be a 0 and my regex failed to match. As soon as I change the last number to be any number then it works. The first number can be anything, that doesn't matter. I even tried the following regex patterns and still wouldn't match

"/\d+\.(\d+)&/"
"/\.(\d+)/"
"/\.(\d+)&/"

Php Version:

php -v
PHP 8.1.1 (cli) (built: Jan  9 2022 20:13:47) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologie

Running on osx m1 Mac, any ideas?

PHP Version

8.1.1

Operating System

m1 osx 12.0.1

Adam2Marsh avatar Jan 15 '22 23:01 Adam2Marsh

Just to saw I've always used https://regexr.com for testing and all the above work as expected.

image

Adam2Marsh avatar Jan 15 '22 23:01 Adam2Marsh

Also tested the above with php version 8.0 and 7.4 and had the same issue.

Adam2Marsh avatar Jan 15 '22 23:01 Adam2Marsh

That's because (string)0.0 === "0". Maybe you're looking for preg_match('/^(\d+)(?:\.(\d+))?$/', $value, $matches);

KapitanOczywisty avatar Jan 15 '22 23:01 KapitanOczywisty

As @KapitanOczywisty mentioned, the reason preg_match fails is because it is a string operation and implicitly coerces 0.0 to the string "0". Both "0" and "0.0" could be valid string representations of the float 0.0 but PHP can't know which one you might want and thus always does the former. The solution for you is to either:

  • Make the fractional part optional (as suggested in the last comment)
  • Convert the float to a uniform string that always has the fractional part
  • Calculate the parts using arithmetic operations instead of string parsing

iluuu1994 avatar Jan 16 '22 00:01 iluuu1994

Thanks @KapitanOczywisty and @iluuu1994; I can see the sense behind why it works that way.

I'll take another stab and look into your ideas. Thank you :)

Adam2Marsh avatar Jan 16 '22 00:01 Adam2Marsh