preg_match - to allow only one dash - php

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.";
}

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

PHP Validation for alpha numeric characters

I have the following code for validating user input for alpha numeric characters
if (!preg_match("/^[A-Za-z][A-Za-z0-9.]*(?:_[A-Za-z0-9]+)*$/", $username)){
echo "invalid username";
}
It checks, whether the input have other characters than (A-Z) (0-9) alpha numeric. Additionally it allows to accept (_) underscore also, but it should be placed in between the strings only as my_name, but it will not accept _myname or myname_.
My question is how can I add a dot(.) character in my above code as same as constrained in underscore as Eg accept (my.name) or (myn.ame) etc but not to accept (.myname) (myname.)
I think this pattern should work for you
$string = 'my_nam.e';
$pattern = '/^[a-z]+([a-z0-9._]*)?[a-z0-9]+$/i';
if ( ! preg_match($pattern, $string))
{
echo 'invalid';
}

Regex to match a string that may contain Chinese characters

I'm trying to write a regular expression which could match a string that possibly includes Chinese characters. Examples:
hahdj5454_fd.fgg"
example.com/list.php?keyword=关键字
example.com/list.php?keyword=php
I am using this expression:
$matchStr = '/^[a-z 0-9~%.:_\-\/[^x7f-xff]+$/i';
$str = "http://example.com/list.php?keyword=关键字";
if ( ! preg_match($matchStr, $str)){
exit('WRONG');
}else{
echo "RIGHT";
}
It matches plain English strings like that dasdsdsfds or http://example.com/list.php, but it doesn't match strings containing Chinese characters. How can I resolve this?
Assuming you want to extend the set of letters that this regex matches from ASCII to all Unicode letters, then you can use
$matchStr = '#^[\pL 0-9~%.:_/-]+$#u';
I've removed the [^x7f-xff part which didn't make any sense (in your regex, it would have matched an opening bracket, a caret, and some ASCII characters that were already covered by the a-z and 0-9 parts of that character class).
This works:
$str = "http://mysite/list.php?keyword=关键字";
if (preg_match('/[\p{Han}]/simu', $str)) {
echo "Contains Chinese Characters";
}else{
exit('WRONG'); // Doesn't contains Chinese 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

php regex ctype

I need a regex to see if the $input ONLY contained alphabetic characters or white spaces also need one to check if $numInput ONLY contained numeric characters or white spaces AND one combined so:
$alphabeticOnly = 'abcd adb';
$numericOnly = '1234 567';
$alphabeticNumeric = 'abcd 3232';
So in all of the above examples alphabetic, numeric, whitespace are allowed ONLY NO symbols.
How can I get those 3 diffrent regular expression?
This should help you
if (!preg_match('/^[\sa-zA-Z]+$/', $alphabeticOnly){
die('alpha match fail!');
}
if (!preg_match('/^[\s0-9]+$/', $numericOnly){
die('numeric match fail!');
}
if (!preg_match('/^[\sa-zA-Z0-9]+$/', $alphabeticNumeric){
die('alphanumeric match fail!');
}
This is pretty basic
/^[a-z\s]+$/i - letter and spaces
/^[\d\s]+$/ - number and spaces
/^[a-z\d\s]+$/i - letter, number and spaces
Just use them in preg_match()
In order to be unicode compatible, you should use:
/^[\pL\s]+$/ // Letters or spaces
/^[\pN\s]+$/ // Numbers or spaces
/^[\pL\pN\s]+$/ // Letters, numbers or spaces

Categories