Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate only natural numbers?

I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1, 2, 3, etc.) without non-digit characters.

My method looks like this:

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

So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3" and even "2.3,2.2"

like image 270
soren.qvist Avatar asked Feb 02 '11 18:02

soren.qvist


1 Answers

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

Anyways, you can use

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

or you can use

$str = (string) $str;
ctype_digit($str);
like image 167
Crayon Violent Avatar answered Sep 21 '22 04:09

Crayon Violent