PHP Regex - value of 1 or more integers

Hi, I am trying to do an input check in PHP to make sure that the entered stock values ​​are at least 1 positive integer and from 0 to 9. Must not contain special characters.

For example, any of the following values ​​must be valid:

7
0
32
47534

The following MUST NOT be valid:

asdf
35/gdf
../34.

etc..

I use the following if statement to check for a positive integer value of $ original_stock.

if (preg_match("/^[0-9]$/", $original_stock)) 
{
    $error .="Original stock must be numerical.";
}

In addition, I have a price field that should be checked as int or double.

If there is a simpler alternative to using regex, that's good too!

Thanks in advance:)

+3
source share
5 answers

Try this regex:

/^\d+$/

, .

int double:

/^\d+\.?\d*$/

, , .

+8

:

/^[0-9]+$/

+ " ". . :

/^\d+$/

- :

/^\d+(\.\d{1,2})?/

, . . (.. .12 .)

, is_int is_float.

; , . preg_match 0, , :

if (!preg_match("/^\+$/", $original_stock)) {
  // error
}

( !).

+2

, , : is_int.

#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
    #Valid, do stuff
}
else {
    #Invalid, do stuff
}

#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
    if (!is_int($s)) {
        $valid = false;
        break;
    }
}
if ($valid) {...}
else {...}
+1
source

I just ran into this exact problem and solved it this way using regex.
I think the problem is your carriage.

/^[0-9]$/

I moved it inside the class and got the desired results.

function validate_int($subject)
{
    //Pattern is numbers
    //if it matches anything but numbers, we want a fail
    $pattern = '/[^0-9]/'; 
    $matches = preg_match($pattern, $subject);
    if($matches > 0)
      return false;
    else
      return true;
  }
+1
source

you can use

is_int
0
source

All Articles