If you demand checking numeric input by preg_match() you should:
- at first add
^ (start of string) and $ (end of string) meta characters to your regexp
- add handling for floats
- consider removing spaces from string (user may decide to input
1 800 instead of 1800)
- use
\d - escape sequence for decimal numbers group
So final regexp would look like: ~^\d+([.,]\d+)?$~.
You should rather use is_numeric() but according to manual it accepts "science format":
Finds whether the given variable is numeric. Numeric strings consist
of optional sign, any number of digits, optional decimal part and
optional exponential part. Thus +0123.45e6 is a valid numeric value.
Hexadecimal notation (0xFF) is allowed too but only without sign,
decimal and exponential part.
Which I personally avoid, this function just allows to input too much and you have to worry about transformation to valid form.
There'are two nice functions intval() and floatval() with just a little example:
$numbers = array( '1.8', '3', 'hello');
foreach( $numbers as $i){
var_dump( $i);
var_dump( intval( $i));
var_dump( floatval( $i));
echo "\n";
}
And output:
string(3) "1.8"
int(1)
float(1.8)
string(1) "3"
int(3)
float(3)
string(5) "hello"
int(0)
float(0)
Which allows you to do this:
php > $str = "3.8";
php > $i = intval( $str);
php > var_dump( $i == $str);
bool(false)
php > $str = "3";
php > $i = intval( $str);
php > var_dump( $i == $str);
bool(true)
You also can use filter_var(), but those functions just doesn't work for me and I'd build function like this:
function get_integer( $input){
if( $input === null){
return null;
}
if( $input === ''){
return null;
}
$i = intval( $input);
if( $i != $input){
return null;
}
return $i;
}
$myCol = get_integer( $_POST['foo']);
if( $myCol === null){
die( 'You naughty boy!');
}
[0-9]will only match a single digit. Also,preg_matchtakes a string as its second parameter, not an array.Notepad++orGVim!