Beginner PHP. Regular expression, excluding characters - php

I am trying to create a regex for my form that will accept lower case characters a-z, upper case A - Z and all numbers.
I have successfully included what needs to be accepted, but what I want to do is exclude the following characters $£*
The code I have so far is as follows:
if (!preg_match("/^[a-zA-Z0-9 ^$£* ]{1,20}$/", $webdata['familypa']))

Your pattern can be accurately/concisely written as:
~^[a-z\d]{1,20}$~i
if(!preg_match('~^[a-z\d]{1,20}$~i',$webdata['familypa'])){
echo 'familypa is not an alpha-numeric string or doesn\'t have a length of between 1 & 20 characters';
}else{
echo 'familypa is all good';
}
Or you can write a more verbose, non-regex method:
*The conditional checks for positive length, then length less than 21, then alpha-numeric.
if($len=strlen($webdata['familypa']) && $len<21 && ctype_alnum($webdata['familypa'])){
echo 'familypa is all good';
}else{
echo 'familypa is not an alpha-numeric string or doesn\'t have a length of between 1 & 20 characters';
}

The regex expression for accepting lower case characters a-z, upper case A - Z and all numbers (considering any number 0-9 ) is the following : regex:/^[a-zA-Z0-9]*$/

Related

Username may contain lowercase characters and numbers

I want to allow lowercase characters and numbers in username field.
But with following conditions...
Only numbers as username NOT allowed (e.g. only mobile number)
Only lowercase characters allowed (e.g. without any number in username)
Lowercase characters + numbers allowed (e.g. combination of lowercase and numbers)
Minimum length 8 characters required
Maximum length 20 characters allowed
What php regex will do it ?
I tried with following, but it forces lowercase + numbers. Only lowercase username not allowing.
$username_pattern = '/^(?=.*[a-z])(?=.*[a-z])(?=.*\d)[a-z0-9]{8,20}$/';
I want only lowercase and/or lowercase+numbers ( min 8 and max 20 ) in username
Help appreciated.
You can simplify it to not allowing only digits
^(?!\d*$)[a-z0-9]{8,20}$
Explanation
^ Start of string
(?!\d*$) Negative lookahead, assert not only digits till end of string
[a-z0-9]{8,20} Match 8-20 times a char a-z or a digit 0-9
$ End of string
Regex demo | Php demo
$username_pattern = '/^(?!\d*$)[a-z0-9]{8,20}$/';
$userNames = [
"1a3b5678",
"1a3b5678abcd",
"12345678",
"1a3b5678abcddddddddddddddddddddddddddddddd",
"1a3B5678",
"a1"
];
foreach ($userNames as $userName) {
if (preg_match($username_pattern, $userName)) {
echo "Match - $userName" . PHP_EOL;
} else {
echo "No match - $userName" . PHP_EOL;
}
}
Output
Match - 1a3b5678
Match - 1a3b5678abcd
No match - 12345678
No match - 1a3b5678abcddddddddddddddddddddddddddddddd
No match - 1a3B5678
No match - a1

preg_match - to allow only one dash

I'm using preg_match and its working to allow; numbers, letters and dash. but i want to limit the dash to 1 only. i tried added {1} before and after the dash but its still allowing more than one. what am i doing wrong?
if (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
} else {
This is the code that i'm using.
Thanks
Make an extra test for the dash count to keep it simple.
if (!preg_match("/^[A-Za-z0-9\-]+$/", $username) || substr_count($username,'-') > 1) {
$nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
}
Since you seem to validate a string that can contain one or zero hyphens in an alphanumeric string, you may use a negative lookahead in your pattern to fail the match if 2 hyphens are found:
"/^(?![^-]*-[^-]*-)[A-Za-z0-9-]+$/D"
^^^^^^^^^^^^^^^^
Pattern details:
^ - start of a string
(?![^-]*-[^-]*-) - fail the match if there are 2 hyphens separated with 0+
chars other than -
[A-Za-z0-9-]+ - 1 or more alphanumeric chars or hyphens
$ - the very end of the string (since /D modifier is used).
See a regex demo (pattern modified to account for a multiline string input).
Note that if you want to disallow - to appear at the start/end of the string, and several consecutive -s, use a more straight-forward pattern:
"/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)?$/D"
where ^[A-Za-z0-9]+ will match 1+ alphanumeric chars at the start of the stirng, and (?:-[A-Za-z0-9]+)?$ will match 1 or 0 occurrences of a - followed with 1+ alphanumeric chars at the end of the string.
$username = "abc-edf-tru-ksk-5-ll-hr-foam-6-inch-queen-anroid-phone-stackoverflow-72-x-70-x-6290321_1";
This below code allow hypens(-) and underscore(_)
if(preg_match('/^[a-zA-Z0-9\-\_]+(-[a-zA-Z0-9\-\_]+)*$/', $username))
{
echo "The username you selected valid characters are hypens,underscores, letters and numbers.";
}
allow only hypen(-)
if(preg_match('/^[a-zA-Z0-9\-]+(-[a-zA-Z0-9\-]+)*$/'), $username))
{
echo "The username you selected valid characters are hypens(only), letters and numbers.";
}
allow only underscore(_)
if(preg_match('/^[a-zA-Z0-9\_]+(-[a-zA-Z0-9\_]+)*$/'), $username))
{
echo "The username you selected valid characters are underscores(only),underscores, letters and numbers.";
}
not allow hypens, underscores and symbols
if(preg_match('/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/'), $username))
{
echo "The username you selected valid characters are letters and numbers.";
}

Regular expression with alpha numeric and need to check length of the string

I have a regular expression which compares if a string is having both alpha and numerical values. But i need to compare if the string is having any special characters and length of the string should be 6.
my current regular expression is
$val = 'A457718';
preg_match('/^[A-Z]|[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/i', $val)
But i need to compare if there are any special characters are there and string length should be 6. Any help would be greatly appreciated.
You don't need a regex to check for string that is 6 characters long and only numerical.
$val = 'A457718';
if (is_numeric($val) && strlen($val) == 6) {
echo 'true';
} else {
echo 'false';
}
Demo: http://sandbox.onlinephpfunctions.com/code/25c426d1bbbfce4a96c8c1ba74cc4a84b66c2435
Functions:http://php.net/manual/en/function.is-numeric.phphttp://php.net/manual/en/function.strlen.php
If for some reason you require it in regex.
preg_match('~^\d{6}$~', $val);
Demo: https://regex101.com/r/oR9bT4/1
The pattern /^[a-zA-Z0-9]{6}$/ will match six characters that are alphanumeric.
if(preg_match('/^[a-zA-Z0-9]{6}$/', 'A45BBB')){
// Is valid
}
for the length, put at the end {0,6} .. this will limit string to be from 0 to 6 characters
This would match any 6-length alphanumeric string:
\b[a-zA-Z0-9]{6}\b
or including the underscore character:
\b\w{6}\b
This should be clarified:
But i need to compare if there are any special characters

PHP regex for password validation

I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.
A-Z
a-z
0-9 >= 2
special chars >= 2
string length >= 8
So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.
Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.
PHP CODE:
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
$special = preg_match('#[\W]{2,}#', $password);
$length = strlen($password) >= 8;
if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
$errorpw = 'Bad Password';
Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>
^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$
Add your special character set to last [...] in the above regex (I put there for now just -+%#).
Explanation:
^ - beginning of line/string
(?=.{8}) - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z]) - ...to ensure we have at least one uppercase char
(?=.*[a-z]) - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])
- ...to ensure we have at least three special chars
(characters other than letters and numbers)
[-+%#a-zA-Z\d]+ - combination of allowed characters
$ - end of line/string
((?=(.*\d){3,})(?=.*[a-z])(?=.*[A-Z])(?=(.*[!##$%^&]){3,}).{8,})
test$ABC5#8 is not valid because you ask more than 2 digits and spec symbols
A-Z
a-z
0-9 > 2
special chars > 2
string length >= 8
For matching length of string including special characters:
$result = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[\s\S]{6,16}$/', $string);
Answer explained: https://stackoverflow.com/a/46359397/5466401

What's a regular expression for a certain ruleset in PHP?

Specifically, it should be 6 or more alphanumerics (0-9 + a-z).
The second character is a letter.
The third character is an odd number.
Any help?
An example regex that matches this for ASCII is
^[0-9A-Za-z][A-Za-z][13579][0-9A-Za-z]{3,}$
PHP code
<?php
$test = '0A1000';
if (preg_match('/^[0-9A-Za-z][A-Za-z][13579][0-9A-Za-z]{3,}$/', $test)) {
// Do some stuff
echo "matched";
}

Categories