equazcion
equazcion

Reputation: 594

Check if a string contains a number, while allowing multiple decimal points?

This is to test version numbers. They need to contain only numbers, but can have multiple decimal points.

For example:

$a = '1.2.3';

is_numeric($a) returns false, and floatval($a) strips out the extra decimal sections, without returning a useful answer to the test.

Is there any PHP function that would do this?

Upvotes: 2

Views: 1020

Answers (2)

dev4092
dev4092

Reputation: 2891

You can use the strcspn function:

$q='1.2.3';

if (strcspn($q, '0123456789') != strlen($q))
  echo "true";
else
  echo "false";

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157947

You can use preg_match():

if(preg_match('~^([0-9]+(\.[0-9]+)*)$~', $string)) {
    echo 'ok';
}

The regex pattern matches from the begin ^ to the end $ of the string and checks if it begins with a number and then contains only numbers - optionally separated by single dots - and ends with a number again.

Upvotes: 3

Related Questions