PHP regex check length without using lookahead - php

Looked at 2 other regex related questions and both were vastly beyond what I need help with X'D.
<?php
$userName = trim($_POST['username']);
if(preg_match("/^[a-zA-Z].*(?(\d)).{8,}$/", $userName)){
echo 'woot!';
I'm not really sure why its failing. I know its checking the first character must be alpha, then go more * but check at the end if its a digit ?(\d)... But why wont it check if the length of my $userName is 8 or more?
if I do
... *(?(\d){8,}
Its going to look for 8 or more digits as opposed to if the string itself is 8 or more.
User must: start with letter, only end in numbers, and can only contain alphaNumeric, must be at least characters 8 long, and treat lower and uppercase the same. Which is to say I need to add an i at the end of my regex.
As so there is no way to work it into a regex aside form look aheads? ^...$.{8,} wouldn't work?

User must: start with letter, only end in numbers, and can only contain alphaNumeric, must be at least characters 8 long, and treat lower and uppercase the same.
You may use this simple regex to meet this requirement:
^[A-Za-z][a-zA-Z\d]{6,}\d$
RegEx Details:
^: Start
[A-Za-z]: Match an ASCII letter at the start
[a-zA-Z\d]{6,}: Match a letter or digit 6 or more times
\d: Match a digit before end
$: end
RegEx Demo

Use the following regex pattern:
^(?=.{8,}$)[A-Z][A-Z0-9]*[0-9]+$
Sample script:
$userName = trim($_POST['username']);
if (preg_match("/^(?=.{8,}$)[A-Z][A-Z0-9]*[0-9]+$/i", $userName)) {
echo "MATCH";
}
Of note, the regex pattern uses (?=.{8,}$) at the start of the pattern. This is a positive lookahead, which asserts that the match is at least 8 characters.
If you don't want to use a lookahead, you may just explicitly check the username length using strlen():
$userName = trim($_POST['username']);
if (preg_match("/^[A-Z][A-Z0-9]*[0-9]+$/i", $userName) &&
strlen($userName) >= 8) {
echo "MATCH";
}

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 - Why is my preg_match not working?

I'm trying to make sure that when the user registers they use a specific series of characters. In my case i want them to enter something like "d1111111" so I want it to be 8 characters in total and to start with the letter d lowercase or uppercase, to allow the other 7 characters to be a number between 0 and 9. All help appreciated, thanks.
here's my code so far
$regex = '/[d][0-9]{8}/';
if(preg_match($regex, $username)){
echo "Valid";
} else {
echo "not a valid username";
}
Use for example
$regex = '/^[dD][0-9]{7}$/';
or
$regex = '/^d\d{7}$/i';
A character class […] matches a single character, [dD] therefore matches the letter d or D.
Alternatively, you can use the i option (also referred to as modifier) at the end of the expression, to let your regular expression match case-insensitively. It is also possible to change the mode inside the expression, I personally have never used that, though.
\d matches any digit and is the same as [0-9]. {7} denotes how many digits to match.
You need ^ and $ to ensure that the regular expression matches the whole username.
For PHP in particular, see PHP's PCRE docs.
Your regex is wrong here. First, there's no need of a character class to capture d. Just a literal d along with start-of-the-string anchor ^.
Now we want the remaining 7 letters to be digits. So it would be following with the end-of-the-string anchor $
$regex = '/^d\d{7}$/'

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.

Regex match complex conditions for username

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)

Categories