is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

Answer from Spudley on Stack Overflow
Top answer
1 of 12
74

is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

2 of 12
12

According to http://www.php.net/manual/en/function.is-numeric.php, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.

preg_match can be slow, and you can have something like 0000 or 0051.

I prefer using ctype_digit (works only with strings, it's ok with $_GET).

<?php
  _GET['id'];
  if (ctype_digit($id)) {
      echo 'ok';
  } else {
      echo 'nok';
  }
?>
🌐
Quora
quora.com › Can-you-explain-preg_match-and-how-to-accept-only-letters-for-name-and-numbers-for-contact-number-in-php
Can you explain preg_match() and how to accept only letters for name and numbers for contact number in php? - Quora
Always trim input and consider character normalization (UTF-8). Combine client-side checks (for UX) with server-side preg_match() validation (security). For phone numbers, prefer using a parsing/validation library (libphonenumber or its PHP ports) when you need robust international validation ...
🌐
UI Bakery
uibakery.io › regex-library › numbers-only-regex-php
Numbers only regex (digits only) PHP
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!
🌐
W3Schools
w3schools.com › php › func_regex_preg_match.asp
PHP preg_match() Function
abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach function global if implements include include_once instanceof insteadof interface isset list namespace new or print private protected public require require_once return static switch throw trait try use var while xor yield yield from PHP Libxml
🌐
DEV Community
dev.to › altsyset › php-pregmatch-to-validate-us-and-ethiopian-phone-numbers-3m59
PHP preg_match to validate US and Ethiopian Phone Numbers - DEV Community
September 4, 2023 - In those cases, we can use the character classes and range limiters we saw above to validated formatted US and Ethiopian phone numbers like this:- $phoneNumber = "0911-223344"; preg_match('/[0-9]{4}-[0-9]{6}/', $phoneNumber);//Simple regex to validate ethiopian phone number preg_match("/[0-9]{3}-[0-9]{3}-[0-9]{4}/", $phoneNumber); // Simple regex to validate US phone number
🌐
PHP
php.net › manual › en › function.preg-match.php
PHP: preg_match - Manual
After the breaking change in 7.4, be aware that count( $matches ) may be different, depending on PREG_UNMATCHED_AS_NULL flag. With PREG_UNMATCHED_AS_NULL, count( $matches ) will always be the maximum number of subpatterns.
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-extract-numbers-from-string-in-php
How to extract numbers from string in PHP ? - GeeksforGeeks
July 23, 2025 - ... <?php // Sample string with numbers $string = "The order numbers are 123, 456, and 789."; // Using preg_match_all to extract numbers preg_match_all('/\d+/', $string, $matches); // Extracted numbers $numbers = $matches[0]; // Print the extracted ...
Top answer
1 of 2
4

Validating a phone number isn't quite as simple as has so far been suggested. Not only do you have to check that the phone number only contains numbers you also have to make sure that it is the correct length. You also need to make sure that you don't make it difficult for the end user to... use... otherwise you'll end up losing customers.

Example:

If I enter my phone number as 09999 999 999 it won't validate with your system. Because it contains spaces a lot of people do enter phone numbers this way and other, more complex, ways.

Code

if(empty($_REQUEST['phone'])){
    //Empty phone number
}
else if(preg_match('/^(0\d{10}|[1-9]\d{9})$/', $_REQUEST['phone'], $matches)){
    //Good phone number
}
else{
    //Bad phone number
}

Regex Explained

  1. ^ - Start of string
  2. ( - Start a capture group
  3. 0\d{10} - Match a 0 followed by an additional 10 numbers
  4. | - ...OR...
  5. [1-9]\d{9} - Match a non-0 number followed by 9 other numbers
  6. ) - Close capture group
  7. $ - Match end of string

Additional Checks

People often add spaces or brackets/punctuation to make a phone number easier to read/remember for a human. Some examples of phone number input might be:

  • (00000) 999 999
  • (0)9999 999 999
  • 09999 999 999
  • 09999999999
  • 9999999999

These would all be valid phone numbers but wouldn't be accepted by your system...

To fix this (and make life for users much easier) you would remove characters from the phone number that aren't numbers and then check it for length.

$phoneNumber = "(09999) 999 999";
$phoneNumber = preg_replace('/[^\d]/', '', $phoneNumber); //Replace non-numbers with nothing
echo $phoneNumber; //Outputs: 09999999999

A Note On Security

I strongly suggest that yo do not use $_REQUEST and instead use $_POST or $_GET as an extra security step. Explicitly using the method that you're expecting the data to come through is one more validation step to make sure that the request is legitimate.

2 of 2
1

elseif (!preg_match('/^[0-9]+$/', $_REQUEST['phone'] ) ) { should do the job. As the RegEx you use stands for the correct phone number, you need to issue the warning if there is no match found, not in case there is a match found.

Find elsewhere
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php preg_match
PHP preg_match - PHP Tutorial
September 18, 2021 - Note that the $offset is in bytes. The preg_match() function returns 1 if it finds a match,0 if it doesn’t, or false on failure. Let’s take some examples of using the preg_match() function. The following example uses the preg_match() to match a number with one or more digits using the \d+ character class: <?php $pattern = '/\d+/'; $str = 'PHP first released in 8 June 1995'; if (preg_match($pattern, $str, $matches)) { print_r($matches); }Copy
🌐
LinuxQuestions.org
linuxquestions.org › questions › programming-9 › php-preg_match-best-way-to-match-numbers-4175678734
[SOLVED] php - preg_match best way to match numbers ?
I have rarely used reg-ex expressions and I thought I could learn a little bit of the technique now. I am converting a thunderbird contacts address
Top answer
1 of 3
6

There are three problems with your regex:

  • You aren't escaping the forward slash. You're using the forward slash as a delimiter, so if you want to use it as a literal character inside the expression, you need to escape it
  • ((.*?)) doesn't do what you think it does. It creates two capturing groups -- one nested inside the other. I assume, you're trying to capture what's inside the parentheses. For that, you'll need to escape the ( and ) characters. The expression would become: \((.*?)\)
  • Your expression doesn't handle whitespace. In the string you've given, there is whitespace between the </a> and the beginning of the number -- </a> (2194). To ignore the whitespace and capture just the number, you need to use \s (which matches any whitespace character). For that, you need to write \s*\((.*?)\)\s*.

The final regular expression after fixing all the above errors, will look like:

$regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';

Full code:

$string = 'Clasificación</a> (2194)  </li>';
$regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';
preg_match($regex , $string, $match);
var_dump($match);

Output:

array(2) {
  [0]=>
  string(32) "Clasificación (2194)  "
  [1]=>
  string(4) "2194"
}

Demo.

2 of 3
2

You forget to espace / in your regex, since you're using the / as a delimiter:

$regex = '/Clasificación<\/a>((.*?))<\/li>/';
//        ^ delimiter    ^^               ^ delimiter
//                       ^^ / in a string which is escaped

Another way can be to change that delimiter, and then you will not have to escape it:

$regex = '#Clasificación<\/a>((.*?))<\/li>#';

See the PHP documentation for more information.

🌐
Alvin Alexander
alvinalexander.com › php › php-preg_match-integer-regex-regular-expression-pattern
A PHP preg_match integer regex pattern matching example | alvinalexander.com
Put all this together, and it means "Test the variable $var to see if it contains one or more numeric digits; because the beginning of line and end of line are specified, that's all that can be in this string, digits. For instance, the string '123' is valid, but a string like 'a123' is not valid." I hope this PHP preg_match integer regular expression pattern (regex pattern) example has been helpful.
🌐
Stack Overflow
stackoverflow.com › questions › 60106938 › how-to-preg-match-in-php-for-numeric-with-fixed-range
preg match - how to preg_match in php for numeric with fixed range? - Stack Overflow
February 7, 2020 - if (!preg_match("/^[1-9][0-9]{7}$/", $PhNum)) { $error .= '<p><label class="text-danger">Only 8 digit numbers are allowed</label></p>'; }
🌐
SitePoint
sitepoint.com › php
Preg_match with regex expression for phone number - PHP - SitePoint Forums | Web Development & Design Community
October 21, 2020 - Also, if you do move your trailing / to the correct location, your pattern is still incorrect - it currently would allow +++++++++ as a valid phone number, also 123879872398712987391827398127398712983719827391827398127397293918837198721 · I already know am not getting it right, regex confuses ...
Top answer
1 of 1
1

The Regex Problem

What you want is something like this:

<?php
$nik=1234567891234567;

var_dump($nik);

if(preg_match('/^[1-9]\d{15}$/', $nik)){
    echo "Contains only numbers";
    exit;
}else{
    echo "Contains non-numeric characters";
    exit;
}

Here's a demo.

This will match a string with exactly 16 characters; the first can be 1-9, but the rest can be any digit. Your regex, /^[1-9][0-9]{16}$/, matches a character in the range 1-9, then 16 characters in the range 0-9, for a total of 17 characters.

Integer Size

Also, your code has a logical flaw: your number is larger than the maximum integer value on a 32-bit system, as stated in the documentation. The largest value on any system can be determined by checking the constant PHP_INT_MAX. For a 32-bit system, this is 2147483647. That has fewer than 16 characters, so your code will not work reliably on a 32-bit system.

Strings Versus Integers

Also, your post said you're getting this info from a user via a form. In that case, you will be receiving a string, not an integer. For example, if your field is named nik, then you would access the info with $_POST['nik'] (for a POST form) or $_GET['nik'] (for a GET form). Then, just use it as a string; it's not really a number, anyway.

Other Considerations

You're checking for a 16-character number. This sounds like something involving credit cards. If you are doing credit card processing, you should know that there are major security implications and compliance issues related to processing cards on your server. I can't give you legal advice, and how to properly process a credit card is much too broad a topic for this site. But I will say this: if this is credit card data, you do not want to do it this way unless you have a very large budget for compliance issues, auditing, and the like. You should look into using PayPal, Stripe, or a similar vendor to handle this.