Reputation: 594
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
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
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