17

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

3
  • Try this ^\d+$ Commented Jan 29, 2018 at 7:25
  • 3
    ctype_digit does exactly what you want 3v4l.org/YcOSo Commented Jan 29, 2018 at 7:30
  • 2
    Are you sure the input was a string? ctype_digit only works with strings, not numbers. Commented Jan 29, 2018 at 7:34

2 Answers 2

27

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

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() php.net/manual/en/function.ctype-digit.php
11

what about

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.