简体   繁体   中英

Regular Expression (avoid float numbers)

I want a pattern to create a "is_id()" function to validate user input before mysql query. The pattern most contain ONLY numbers, my problem is avoid the float numbers:

function is_id($id) {          
    $pattern = "/^[0-9]+/";      
        if(preg_match($pattern,$id)) {      
            echo "ok";      
        } else {      
            echo "error";       
        }    
} 


is_id(0) // error  
is_id(-5) // error  
is_id(-5.5) // error  
is_id(1.5) // ok <-- THIS IS THE PROBLEM  
is_id(10) // ok  
is_id("5") // ok  
is_id("string") // error

$表示要匹配的行/字符串的结尾。

/^[0-9]+$/

You're missing the trailing $ in your pattern. In is_id(1.5) your pattern is matching the 1 and stopping. If you add a trailing $ (as in ^[0-9]+$ ) then the pattern will need to match the entire input to succeed.

You don't need regex for this, you can use a simple check like so:

function is_id($id)
{
    return ((is_numeric($id) || is_int($id)) && !is_float($id)) && $id > -1
}

The output is as follows:

var_dump(is_id(0));        // false - are we indexing from 0 or 1 ?
var_dump(is_id(-5));       // false
var_dump(is_id(-5.5));     // false
var_dump(is_id(1.5));      // false
var_dump(is_id(10));       // true
var_dump(is_id("5"));      // true
var_dump(is_id("string")); // false

I favour ircmaxell's answer.

Why use a regex? Why not check types (this isn't as tiny as the regex, but it may be more semantically appropriate)

function is_id($n) {
    return is_numeric($n) && floor($n) == $n && $n > 0;
} 

is_numeric() verifies that it's either a float, an int, or a number than can be converted.

floor($n) == $n checks to see if it's indeed an integer.

$n > 0 checks to see if it's greater than 0.

Done...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM