Regex match complex conditions for username - php

I need to check if string has anything else than what specified below
it must begins from letter (either uppercase or lowercase)
can have alphabetical characters
can have numeric characters
can have dashes
can have minus sign -
can have underscore _
can have comas ,
can have dots .
length from 4 to 35 caracters no more no less
everything else should not be in this string have have
i am stuck on this:
preg_match('/^[\w]{4,35}$/i', $username)

if( !preg_match('/^[a-zA-Z][a-zA-Z0-9_,.-]*$/', $username ))
echo "failed\n";

preg_match('/^[\w]{4,35}$/i', $username)
OK lets see what this doesn't work :
Match the beginning of the string, followed by [a-zA-Z0-9_] at least 4 times with a maximum of 35 times. This is quite different from your requirements.
Instead what you should use :
/^[a-zA-Z][-,.\w]{3,34}$/
The case sensitivity i modifier is not needed. Also I don't think this is exactly what you want. Usually you would need to specify a minimum length which you don't. This can match "a" for example (not a good username)

Related

regex for password 6-12 chars one digit, one uppercase

I'm trying to check user password with this regular exp:
$regex='/^(?=.*[A-Za-z0-9#])(?=.*\d)[a-zA-Z0-9#]{6,12}$/';
if(isset($_POST['password']) && strlen($_POST['password'])>=6 &&
strlen($_POST['password']<=12) && preg_match($regex, $_POST['password'])){
echo 'ok';
}else{echo 'invalid password';}
I'd like the password to be from 6 to 12 chars, at least one digit and at least one Uppercase.
It doesn't work if the password is something like 12Hello instead it works with Hello12 , someone could please help?
Thanks
Your character class is too broad. You need to check for things separately.
^(?=.*[A-Z])(?=.*\d).{6,12}$
(?=.*[A-Z]) is at least one upper case character.
(?=.*\d) is at least one number
and .{6,12} is 6-12 characters (that aren't new lines)
The ^$ are anchors ensuring the full string matches.
In your regex your character class [A-Za-z0-9#] allows an uppercase character, lowercase, number, or # (which doesn't ensure you have 1 uppercase character). You also don't need the strlen functions if using this regex.
Try this one:-
Minimum 6 character
Atleast 1 uppercase character
At least one digit
Expression:
"/^(?=.*?[0-9])(?=.*[A-Z]).{6,12}$/"

PHP Regex - Minimum of 8 characters, 1 letter, 1 number

So I thought I had this right?
if(!preg_match('^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+.{7,}$', $passOne)) {
$msg = "Password does not contain at least 1 number/letter, 8 character minimum requirement.";
}
I test it over at https://regex101.com/ and put ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+.{7,}$ to work and things like RubyGlue12 pass and is a match and other things that aren't.
But no matter what, I cannot make any match in the actual PHP code. Even if the POST is a variable manually.
edit: $_POST['password'] is $passOne
Help?
You have .+.{7,} that does not make much sense since it means match any characters 1 or more times, and then any characters 7 or more times.
1 letter, 1 digit and min 8 characters regex will look like
(?i)^(?=.*[a-z])(?=.*\d).{8,}$
Regex explanation:
(?i) - Turning case sensitivity off (unless you need to check for 1 uppercase and 1 lowercase letters - then, remove the i flag and replace (?=.*[a-z]) with (?=.*[a-z])(?=.*[A-Z]))
^ - Start of string
(?=.*[a-z]) - Positive look-ahead requirement to have at least 1 letter
(?=.*\d) - Positive look-ahead requirement to have at least 1 digit
.{8,} - At least 8 characters
$ - End of string.
And PHP code is:
$re = "/^(?=.*[a-z])(?=.*\\d).{8,}$/i";
$passOne = "RubyGlue12";
//$passOne = "eee"; // uncomment to echo the error message
if(!preg_match($re, $passOne)) {
echo "Password does not contain at least 1 number/letter, 8 character minimum requirement.";
}
And yes, with preg_match function, you must use some regex delimiters. I am using / here.
Here's a regex that tests for what the password should not be, instead of what it should be.
/^(.{0,7}|[^a-z]*|[^\d]*)$/i
Example:
if (preg_match('/^(.{0,7}|[^a-z]*|[^\d]*)$/i', $passOne)) {
echo "Validation failed.\n";
}
Explanation:
There are essentially 3 separate tests within the regex (each separated by a |, and each are case-insensitive due to the i option at the end). If it passes any of the tests, then the entire validation fails.
Test 1: Does the entire string only contain 0-7 characters? Fail.
Test 2: Does the entire string contain no alpha characters? Fail.
Test 3: Does the entire string contain no digits? Fail.

php preg_match only numbers, letters and dot

I have been searching for 2 hours now and I still don't get it.
I need to evaluate the input of the account name. That can ONLY contain numbers (0-9), letters (a-z and A-Z) and the dot (.).
Everything else is forbidden. So, no underscore (_), plus (+) and so on.
Valid accounts should look like, e.g.:
john.green
luci.mayer89
admin
I tried many preg_match/regex examples but I don't get it working. Whenever I do echo preg_match(...) I get 1 as true.
$accountname = "+_#luke123*";
echo preg_match("/[a-z0-9.]/i", $accountname);
//--> gives back 1 as true
In addition, it would be great to control that the account name starts with at least 2 letters or numbers and ends with at least 1 letter or number - but I am far, far away from that.
You need to use anchors and a quantifier:
echo preg_match("/^[a-z0-9.]+$/i", $accountname);
Your string +_#luke123* contains a letter and a number, thus there is a match. If we tell the engine to only match the whole string from beginning (^) to end ($), we'll make sure this will not match. + ensures we capture not just 1, but all characters.
See this demo, now there is no match!
EDIT:
Since you also need to check these conditions:
string must start with 2 or more letters or numbers and end with 1 or
more letters or numbers
I can suggest this ^[a-z0-9]{2,}[a-z0-9.]*[a-z0-9]+$ regex (must be used with i option) that means:
Starts with 2 or more letters or numbers
then follow any number of digits, letters or periods
and ends in 1 or more letters or numbers.
Another demo

What am I doing wrong with this Regex?

To be honest, I don't really get RegEx. So I'm completely oblivious as to where I'm going wrong here.
I'm looking for a RegEx that accepts alphanumeric characters only (and underscores, it's for usernames). I've searched around here and found numerous example RegExes that I've tried and not one of them has worked.
Among others, which I've mostly gotten from answers around here, I've tried
^[a-zA-Z0-9_]*$
/[^a-z_\-0-9]/i
/^\w+$/
To match these, I've tried (with each of the regexes)
if(preg_match("/^\w+$/", $username)) {
//don't accept
}
and
if(!preg_match("/^\w+$/", $username)) {
//don't accept
}
and
if(preg_match("/^\w+$/", $username) == 1) {
//don't accept
}
and
if(preg_match("/^\w+$/", $username) == 0) {
//don't accept
}
etc...
Each and every single time it's accepting special characters (I've tried &, $, ^, and %).
What exactly am I doing wrong here? Is it the format of the RegEx? Is it how I'm asking it to check?
Also, what exactly is the return type I get if it's found special characters? (i.e One I don't want to accept)
preg_match returns 1 if the input string matched the pattern you gave, and 0 if it didn't.
You want each character in your usernames to be alphanumeric (plus underscore). One PCRE way of expressing that is with a character class inside square brackets, like this one: [A-Za-z0-9_]. There are a couple of ways you could use this basic class to do what you want.
One way is a "negative" search: try to match a non-alphanumeric character, and if you do, then the test fails. For this, we just add a carat at the front of the character class. This means we're matching any character not in that set.
So, the following pattern matches "any non-alphanumeric, non-underscore character." Here, a match means an invalid username:
if (preg_match('/[^A-Za-z0-9_]/', $username)) {
// invalid username
}
Or, you could do the opposite kind of match, where you give a pattern for a valid username and check if you match that. This time, we don't change the character class itself at all, but we add the + quantifier after it, meaning we're matching one or more of the "good" characters.
Additionally, we wrap the ^ and $ beginning-and-end-of-string anchors around our pattern. (It's a little confusing, but a carat at the beginning of a pattern has a completely different meaning from a carat at the beginning of a character class, within the brackets).
The end result is a pattern that means: "1 or more alphanumeric characters (plus underscore) and nothing else." A match on this one means a valid username:
if (preg_match('/^[A-Za-z0-9_]+$/', $username)) {
// valid username
}
if (preg_match("^[a-zA-Z0-9_]+$", $username) === 1) {
// Good username
}
else {
// Bad username
}
The use of the strict equality operator (===) means we're comparing what preg_match() returns to 1, the number, not the boolean value. If it returns a 0, it means there are no matches, a boolean false, an error occored. Check out the page for preg_match for more information: http://php.net/manual/en/function.preg-match.php
Per the PHP manual *preg_match* will return 0 if it can't find a successful match with your regex and FALSE if en error occurs. So if you want to make sure you're testing for 0, and not something which can evaluate to false, you should use the === operator.
If you only want letters and underscores you can use a character class of [a-z_] which specifies that the range of characters for a to z and the _ symbol will match. And the + following the class specifies that you want one or multiple of the same. The ^ says the pattern must match from the beginning of the text, while the $ says that the pattern must match up until the end of the text.
if (preg_match("/^[a-z_]+$/i", $text_variable) === 1) {
//"A match was found.";
} else {
//"A match was not found.";
}
Regex is very easy to understand if you get the basics :)
I'll try to explain to you all three expressions you tried:
With ^[a-zA-Z0-9_]*$ string will be matched which:
^ // from the beginning...
[a-zA-Z0-9_] // contains only characters a-z or A-Z or 0-9 or _ sign
* // and has 0 or more of such characters
$ // to the end
Matched strings for example:
(empty string - since you told 0 or more characters)
abc09
fidjwieofoj4fio3j4fiojrfioj3ijfo
000000000000000000000
__________
and_many_many_more_as_long_as_they_contain_alpha_characters_and___sign
With /[^a-z_-0-9]/i string will be matched which:
[^a-z_\-0-9]
// ^ means "the opposite" so that subset describes characters
// which are not included in it
// (are not a-z or _ sign, or - dash sign, or 0-9 numbers)
i modifier
// stands for case insensitive, all letters are treated as lowercase
You did not add * or ? or + after the subset so basically you are looking for one character only, and because you did not put your regexp between ^ and $ signs, this expression will finally match any text which contains at least one character which is not A-Z or a-z, or _ sign, or - dash sign, or 0-9 numbers.
Matched strings for example:
!
a>a
A<9
ffffffffff.dflskfdfd
00000,
]]]]]]]]]]]]]]]]]]
and so-on
With /^\w+$/ string will be matched which:
^ // from the beginning
\w // contains only characters a-z or A-Z or 0-9 or _ sign
+ // and the string must be at least 1 character long
$ // to the end
Probably the most useful regular expression. Remember, \w is just an alias for [a-zA-Z0-9_]. This regexp will match only whole string which is not empty and contains only alphanumeric characters and _ sign.
Matched strings for example:
mike
alice
bob10
0000000000
1111
9
php
user_example
Hope that helps. To you, most useful expression imvho to match valid usernames would be /^\w{3,15}$/ as it would match any string which is 3 to 15 characters long and consist only of alphanumeric characters and the underscore sign (a-z A-Z 0-9 _).
Try this:
<?php
function isValidUsername($username)
{
return preg_match('/^\w{3,15}$/', $username) == 1;
}
echo isValidUsername('mike999') ? 'Yes' : 'No' , '<br>';
echo isValidUsername('alice!') ? 'Yes' : 'No';
Cheers.

php regex needed to check that a string has at least one uppercase char, one lower case char and either one number or symbol

Hi I need to use php's pregmatch to check a string is valid. In order to be valid the string needs to have at least one uppercase character, at least one lowercase character, and then at least one symbol or number
thanks
You can achieve this by using lookaheads
^(?=.*[a-z])(?=.*[A-Z])(?=.*[\d,.;:]).+$
See it here on Regexr
A lookahead is a zero width assertion, that means it does not match characters, it checks from its position if the assertion stated is true. All assertions are evaluated separately, so the characters can be in any order.
^ Matches the start of the string
(?=.*[a-z]) checks if somewhere in the string is a lowercase character
(?=.*[A-Z]) checks if somewhere in the string is a uppercase character
(?=.*[\d,.;:]) checks if somewhere in the string is a digit or one of the other characters, add those you want.
.+$ Matches the string till the end of the string
As soon as one of the Assertions fail, the complete regex fail.
If the match has to be in the order you've described, you could use
$result = preg_match('/[A-Z]+[a-z]+[\d!$%^&]+/', $string);
If the characters can be in any order I'm not so sure, without doing three separate checks like so:
$result = (preg_match('/[A-Z]+/', $string) && preg_match('/[a-z]+/', $string) && preg_match('/[\d!$%^&]+/', $string));
As people have pointed out below, you can do this all in one regular expression with lookaheads.
According to your request:
[A-Z]+ Match any uppercase char
[a-z]+ Match any lowercase char
[\d§$%&]+ Match a number or special chars (add more special if you need to)
The result would look like this: [A-Z]+[a-z]+[\d§$%&]+
This isn't ideal though. You might want to check Regexr and try what kind of regex fits your requirements.
If you want these not to be necessarily in order, you need a lookahead. The following expression will validate for at least one lower char, one upper char and one number:
$result = preg_match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])', $string);
You can put a lot of special chars with the numbers, like this:
$result = preg_match('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9$%])', $string);

Categories