Regex to validate only natural numbers? - php

I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1, 2, 3, etc.) without non-digit characters.
My method looks like this:
function is_natural($str)
{
return preg_match('/[^0-9]+$/', $str) ? false : $str;
}
So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3" and even "2.3,2.2"

perhaps you can clarify the difference between a "number" and a "digit" ??
Anyways, you can use
if (preg_match('/^[0-9]+$/', $str)) {
// contains only 0-9
} else {
// contains other stuff
}
or you can use
$str = (string) $str;
ctype_digit($str);

The problem with /^[0-9]+$/ is that it also accepts values like 0123.
The correct regular expression is /^[1-9][0-9]*$/.
ctype_digit() suffers the same problem.
If you also need to include zero use this regex instead: /^(?:0|[1-9][0-9]*)$/

Use ctype_digit() instead

I got an issue with ctype_digit when invoice numbers like "000000196" had to go through ctype_digit.
So I have used a:
if (preg_match('/^[1-9][0-9]?$/', $str)) {
// only integers
} else {
// string
}

Related

Check input contains either pure numeric characters or pure alpha character using single regular expression

I have a function which will return true if input is pure numeric or alphabate else it will return false. This function is working fine.
function checktype($a)
{
if (preg_match('/^\d+$/', $a)) { //check numeric (can use other numeric regex also like /^[0-9]+$/ etc)
$return = true;
} else if (preg_match('/^[a-zA-Z]+$/', $a)) { //check alphabates
$return = true;
} else { //others
$return = false;
}
return $return;
}
var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)
No I tried to optimized this function by removing conditions so I modified code to:
function checktype($a)
{
$return = (preg_match('/^\d+$/', $a) || preg_match('/^[a-zA-Z]+$/', $a)) ? true:false;
return $return;
}
var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)
Now in third step I tried to merge both regex in single regex so I can avoid two preg_match function and got stuck here:
function checktype($a)
{
return (preg_match('regex to check either numeric or alphabates', $a)) ? true:false;
}
I tried a lot of combinations since 2 days by using OR(!) operator using not operator(?!) but no success at all.
Below some reference website from which i pick expression and made some combinations:
http://regexlib.com/UserPatterns.aspx?authorid=26c277f9-61b2-4bf5-bb70-106880138842
http://www.rexegg.com/regex-conditionals.html
OR condition in Regex
Regex not operator (come to know about NOT operator)
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regular+expression+not+condition (come to know about NOT operator)
So here main question is, is there any single regex pattern to check string contains pure numeric value or pure alphabates?
Note: Alternative solution can be check string is alphanumeric and then return true or false accordingly. Also php inbuilt function like is_numeric and is_string can be used, but I am more curious to know the single regex pattern to check weather string conains pure numeric digit or pure alphaba digits.
A one regex to check if a string is all ASCII digits or all ASCII letters is
'/^(?:\d+|[a-zA-Z]+)$/'
See regex demo
This regex has two things your regexps do not have:
a grouping construct (?:....)
an alternation operator |.
Explanation:
^ - start of string
(?:\d+ - one or more digits
| - or...
[a-zA-Z]+) - one or more ASCII letters
$ - end of string
If you need to make it Unicode-aware, use [\p{L}\p{M}] instead of [a-zA-Z] (and \p{N} instead of \d, but not necessary) and use the /u modifier:
'/^(?:\p{N}+|[\p{L}\p{M}]+)$/u'
And in case you want to really check that from the beginning to end, use
'/\A(?:\p{N}+|[\p{L}\p{M}]+)\z/u'
^^ ^^
or
'/^(?:\p{N}+|[\p{L}\p{M}]+)$/Du'
The $ without /D modifier does not match the string at its "very end", it also matches if there is a newline after it as the last character.

Php only numbers Validating function

I would like to create a validate function for numbers only, actually I have those ones that works fine, and I tried to create one myself, but it's unfortunately not working. Here are the alphanumeric and others working fine :
// Validators
private function custom($validator, $value)
{
return call_user_func($validator, $value, $this->request, $this->id);
}
private function alphanumeric($value, $custom)
{
return preg_match('/^(['.$custom.'a-z0-9_]*)$/i', $value);
}
private function valid_email($value)
{
return preg_match('/^\S+#\S+\.\S+$/', $value);
}
And the one I tried to create by modifying the alphanumeric one :
private function numbers_only($value, $custom)
{
return preg_match('/^(['.$custom.'0-9_]*)$/i', $value);
}
What's wrong with this one ?
EDIT :
I also have a JS helping with the form, for alphanumeric it's :
Form.prototype.alphanumeric = function(value, custom)
{
return !value.replace(new RegExp('['+custom+'a-z0-9_]', 'ig'), '').length;
};
What would be the JS for numeric only ?
Use
is_numeric($value);
return is true or false
If you want only numbers, remove the $custom part from the function. The /i implies case-insensitive matching, which is not relevant for numeric matches, and so can be removed.
private function numbers_only($value)
{
return preg_match('/^([0-9]*)$/', $value);
}
The expression above will match zero or more numbers, so blank input is allowed. To require at least one number, change * to + as in
return preg_match('/^([0-9]+)$/', $value);
And the [0-9]+ can be abbreviated as \d+. Since you are not capturing the value inside a an array of matches, there is no need for the extra overhead which is added by including the () capture group. That can be omitted as well.
return preg_match('/^\d+$/', $value);
Or skip the regex entirely...
Finally, if you've gotten this far and are matching only integers, it is far easier and less resource-intensive to just do:
// If you really intend to match numbers only, and not all numeric values
// which might include .,
function numbers_only($value)
{
return ctype_digit(strval($value));
}
In PHP, for a "only numbers" validation you can use different approaches:
is_int or is_integer
is_numeric
regular expressions
ctype_digit
filter_var
is_integer()
for this function these values are are not valid: "0010", "123"
is_numeric()
for this function these values are valid: 1.3, +1234e44 and 0x539
filter_var()
for this function a value as "00123" is not valid
CONSLUSION
it seems that only regex and ctype_digit work always fine.
TEST
a simple test here

PHP regex expression to find if a string contains YYYY-MM-DD

I would like to check if a URL (or any string) contains any form of the following pattern ####-##-##
Does anyone have a handy str_replace() or regular expression to do that?
something like:
contains_date_string($string);
returns true if $string contains ####-##-##
Thank you!!!
if (preg_match('/\b\d{4}-\d{2}-\d{2}\b/', $str)) {
// ...
}
If the word boundary (\b) doesn't do the trick, you could try negative lookbehind and lookaheads:
if (preg_match('/(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/', $str)) {
// ...
}
As an additional validation, you could use checkdate() to weed out invalid dates such as 9999-02-31 as mentioned in this answer.
Use preg_match in conjunction with checkdate:
function contains_date($str)
{
if (preg_match('/\b(\d{4})-(\d{2})-(\d{2})\b/', $str, $matches))
{
if (checkdate($matches[2], $matches[3], $matches[1]))
{
return true;
}
}
return false;
}
'/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/'
'Makes sure things like 1998-13-32 won't get past and validate.'
I got this from google... http://www.devnetwork.net/viewtopic.php?f=29&t=13795
Looks promising. Hope this will help someone on the search for the same as stackoverflow is the most accessible SEO wise.
The test given here should work:
if (preg_match('#[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])#', $str)) {
// do something
}
Whatever regex you choose, be careful! When a machine sees 2004-04-01, it won't be able to distinguish between January 4th and April Fools day unless you tell it otherwise...

Regex with + sign

I'm using this code to validate string.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
How if I want to validate if the number contain "+" sign in front or not?
Such as :
$countrecipient ='+0123456789';
and still need to validate the rest of the string.
I tried this:
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
{
echo "Ok";
}
else
{
echo "Error";
}
It works in my pc but I'm not sure why my customer is complaining it shows him error.
Thank you.
For an optional plus in front you could use:
preg_match('/^\+?[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient);
Notice how I have escaped the + with a backslash? This is because it is a regex keyword which means 1 instance or more.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
You're making things unnecessarily complicated. "[0]{1}[1]{1}[0-9]{1}" reduces to simply "01[0-9]".
To have an optional + on the front, your basic idea of using [+] should work. Let's see...
$countrecipient ='+0123456789';
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
...again this can be simplified, but it simplies to /^[+]601[0-9][0-9]{7}?$/. Where did the 6 after the + come from? Does this account for your problem?
Plus has a special meaning in PCRE, it's called quantifier and has meaning of {1,}.
You may either put in into character group specification like this [+] which would literally mean one of following characters: array( '+') or escape it with \ so you'll get: \+.
Also adding {1} is implicit and you don't have to add it after one character. If you were doing this matching foo would look like: f{1}o{1}o{1}, ehm f{1}o{2} instead of foo :)
If you want to match both 0123456789 and +012345678 you should use {0,1} which has "shortcut" ?. Than your pattern would look like: /\+?/. I guess your desired regexp is:
/^\+?0?1?[0-9]([0-9]{7})?$/
The simplified form of your regex is
/\+?01[0-9]{8}/
However I recommend you use intval, is_int, ctype_digit to accomplish this.
if(intval($str)<=100000000){
// found it.
}
Based on regexp you put in the section you tried: "...preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/'..."
If you would validate the string AND check if there is a '+' or not, you could use something like this:
if(preg_match('/(\+)?6011[0-9][0-9]{7}?$/', $countrecipient, $matches))
{
if ($matches[1] == '+') {
echo "Ok WITH PLUS";
} else {
echo "Ok without PLUS";
}
}
else
{
echo "Error";
}

PHP Regex - Value of 1 or more integers [duplicate]

This question already has answers here:
php validate integer
(7 answers)
Closed 9 years ago.
Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.
For example, any of the following values should be valid:
7
0
32
47534
The following SHOULD NOT be valid:
asdf
35/gdf
../34.
etc..
I'm using the following if statement to check for the positive integer value of "$original_stock".
if (preg_match("/^[0-9]$/", $original_stock))
{
$error .="Original stock must be numerical.";
}
Additionally, I have a price field which should be validated as either an int or a double.
If there's an easier alternative to using regex, that's okay too!
Thanks in advance :)
Try this regexp:
/^\d+$/
The issue with your existing regexp is that it only matches strings with exactly one digit.
As for validating an int or a double:
/^\d+\.?\d*$/
Note that that regexp requires that there be at least one digit.
Use:
/^[0-9]+$/
The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:
/^\d+$/
For floats, try something like:
/^\d+(\.\d{1,2})?/
This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)
To save yourself some headaches, you can also use the is_int and is_float functions.
Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:
if (!preg_match("/^\+$/", $original_stock)) {
// error
}
(note the !).
You may want to use the
is_int
Don't reinvent a wheel slower than an existing one, use a motorcycle: is_int.
#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
#Valid, do stuff
}
else {
#Invalid, do stuff
}
#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
if (!is_int($s)) {
$valid = false;
break;
}
}
if ($valid) {...}
else {...}
I just ran into this exact problem and solved it this way using the regex.
I think the problem is your caret ^.
/^[0-9]$/
I moved it inside the class and got the results I needed.
function validate_int($subject)
{
//Pattern is numbers
//if it matches anything but numbers, we want a fail
$pattern = '/[^0-9]/';
$matches = preg_match($pattern, $subject);
if($matches > 0)
return false;
else
return true;
}

Categories