16

I want to detect if a string I have contain only number, not containing a letter, comma, or dot. For example like this:

083322 -> valid
55403.22 -> invalid
1212133 -> valid
61,23311 -> invalid
890022 -> valid
09e22 -> invalid

I already used is_numeric and ctype_digit but it's not valid

simple guy
  • 635
  • 1
  • 6
  • 15
  • Try this `^\d+$` – Gurmanjot Singh Jan 29 '18 at 07:25
  • 3
    `ctype_digit` does exactly what you want https://3v4l.org/YcOSo – u_mulder Jan 29 '18 at 07:30
  • 2
    Are you sure the input was a string? `ctype_digit` only works with strings, not numbers. – Barmar Jan 29 '18 at 07:34
  • 1
    I know this is several years old now, but the suggested duplicate is for Javascript, whereas this question is about PHP so is not particularly helpful. – Steven Green Feb 23 '22 at 13:28
  • I have added a PHP dupe target as well @Steven When this question was posted in 2018, there will be at least 10 other pages already dedicated to this task. This is what I call a super-duplicate. If contributors were more discerning, this page would have been closed without any answers at all. – mickmackusa Aug 06 '22 at 06:37

2 Answers2

25

You want to use preg_match in that case as both 61,23311 and 55403.22 are valid numbers (depending on locale). i.e.

if (preg_match("/^\d+$/", $number)) {
    return "is valid"
} else {
    return "invalid"
}
Kasia Gogolek
  • 3,374
  • 4
  • 33
  • 50
  • This could match digits in other locales that aren't 0-9 which isn't what you want. Replace \d with [0-9] or use ctype_digit() https://www.php.net/manual/en/function.ctype-digit.php – PHP Guru Aug 03 '23 at 07:27
10

what about

if (preg_match('/^[0-9]+$/', $str)) {
  echo "valid";
} else {
  echo "invalid";
}