Im checking for validation for both integer and float. preg('/^[0-9]+(.[0-9]+)?$/',$str) This works fine 12,12.05 But not for .12
Any suggestions?
Thanks in advance, kumar.
Make that
preg('/^[0-9]*(\.[0-9]+)?$/',$str)
+ means the element will be repeated one or more times, * means it will be repeated zero or more times.
., and this regex matches empty string.Yep try this:
if((int) $str != $str)
{
//error
}
if((float) $str != $str)
{
//error
}
This should do the trick, and I suppose it will work faster than the regex. Additonally you can check after that (float) $str <= 0 -> another error, etc.
I would bet on regex for more complicated validations, where the with standard routines you have to write some chunk of code, such as email validation, mask(pattern) input and so on.
You could use a combination of is_float and is_int
however, both are pretty much covered by is_numeric
<?php
$tests = array(
"42",
1337,
"1e4",
"not numeric",
array(),
9.1
);
foreach ($tests as $element) {
if (is_numeric($element)) {
echo "'{$element}' is numeric", PHP_EOL;
} else {
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
Output:
'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
Is Float Example:
<?php
if (is_float(27.25)) {
echo "is float\n";
} else {
echo "is not float\n";
}
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7)); //Scientific Notation
var_dump(is_float(true));
?>
is float
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)
and Is_int example:
<?php
if (is_int(23)) {
echo "is integer\n";
} else {
echo "is not an integer\n";
}
var_dump(is_int(23));
var_dump(is_int("23"));
var_dump(is_int(23.5));
var_dump(is_int(true));
?>
is integer
bool(true)
bool(false)
bool(false)
bool(false)
I suggest is_numeric function in PHP that has very better performance than regex functions.
is_numeric return true for ALL of these items:
$s = 123;$s = '123';$s = 123.456;$s = '.456';$s = '-.456';you can see it in action here.