Regex for checking only natural numbers?

I recently found out that the method I used to validate data entry takes on some values ​​that I don't particularly like. I only need to take the natural numbers ( 1, 2, 3etc.) without character, without numbers.

My method is as follows:

function is_natural($str)
{
   return preg_match('/[^0-9]+$/', $str) ? false : $str;
}

Therefore, it should return false if it finds anything else but an integer natural number. The problem is that it accepts strings of type "2.3"and even"2.3,2.2"

+5
source share
4 answers

perhaps you can clarify the difference between a "number" and a "digit"

Anyway you can use

if (preg_match('/^[0-9]+$/', $str)) {
  // contains only 0-9
} else {
  // contains other stuff
}

$str = (string) $str;
ctype_digit($str);
+14

/^[0-9]+$/ , , 0123. /^[1-9][0-9]*$/.

ctype_digit() .

, : /^(?:0|[1-9][0-9]*)$/

+14
+2

ctype_digit, , "000000196", ctype_digit.

, a:

if (preg_match('/^[1-9][0-9]?$/', $str)) {
  // only integers
} else {
  // string
}
-1

All Articles