Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string only contains numbers in php [duplicate]

Tags:

string

regex

php

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

like image 511
simple guy Avatar asked Jan 29 '18 07:01

simple guy


People also ask

How do I check if a string contains only numbers in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.


2 Answers

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"
}
like image 196
Kasia Gogolek Avatar answered Sep 21 '22 19:09

Kasia Gogolek


what about

if (preg_match('/^[0-9]+$/', $str)) {
  echo "valid";
} else {
  echo "invalid";
}
like image 35
Nikos Gkogkopoulos Avatar answered Sep 18 '22 19:09

Nikos Gkogkopoulos