Numbers only regex (digits only) PHP

Numbers only regex (digits only) PHP

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

"/^\\d+$/"

Test it!
/^\d+$/

True

False

Enter a text in the input above to see the result

Example code in PHP:

// Validate if a string is a valid number
$number_validation_regex = "/^\\d+$/"; 
echo preg_match($number_validation_regex, '42'); // returns 1

// Extract number from a string
$extract_number_pattern = "/\\d+/";
$string_to_match = 'Your message was viewed 203 times.';
preg_match_all($extract_number_pattern, $string_to_match, $matches);
print_r($matches[0])// matches[0] is ['203']

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

"/^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$/"

Test it!
/^(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)$/

True

False

Enter a text in the input above to see the result

Example code in PHP:

// Validate if a string is a valid real number
$number_validation_regex = "/^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$/"; 
echo preg_match($number_validation_regex, '121220.22'); // returns 1

// Extract real number from a string
$extract_number_pattern = "/(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)/";
$string_to_match = 'Pi equals to 3.14';
preg_match_all($extract_number_pattern, $string_to_match, $matches);
print_r($matches[0])// matches[0] is ['3.14']

Test it!

True

False

Enter a text in the input above to see the result

Notes on number only regex validation

In PHP you can also validate number by using is_numeric function:

is_numeric("123") // returns TRUE