This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 6 years ago.
i have this function:
public static function encPasswordCheckFailed($password)
{
if (!preg_match('/[A-Z]+/', $password)){
return true;
}
if (!preg_match('/[a-z]+/', $password)){
return true;
}
if (!preg_match('/[0-9]+/', $password)){
return true;
}
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
return false;
}
and now i want to force the user to have at least 1 Uppercased Letter, 1 Lowercased Letter, 1 Number and 1 Specialcharacter.
I'm having the problem with this:
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
All other requirements work. I have only a problem with the specialcharacters.
Can someone tell me the correct pattern for these specialcharacters: !##$%^&*()-+<>
i've read some of the answers from here, here and here but they didn't help me further...
You may need to escape some special characters used by the Regex Engine. And by the way, you could as well do that in one Go as shown below. Quick-Test Here.
<?php
/*public static*/ function encPasswordCheckFailed($password) {
// THIS READS:
// IF THE PASSWORD DOES CONTAIN AN UPPER-CASE CHARACTER
// AND ALSO DOES CONTAIN A LOWER-CASE CHARACTER
// AND STILL DOES CONTAIN A NUMERIC CHARACTER
// AND EVEN MORE, DOES CONTAIN ANY OF THE SPECIFIED SPECIAL CHARACTERS
// RETURN FALSE OTHERWISE RETURN TRUE
if (preg_match('/[A-Z]+/', $password) && // CHECK FOR UPPERCASE CHARACTER
preg_match('/[a-z]+/', $password) && // AND CHECK FOR LOWERCASE CHARACTER
preg_match('/[0-9]+/', $password)&& // AND CHECK FOR NUMERIC CHARACTER
preg_match('/[\!##$%\^&\*\(\)\-\+<>]+/', $password) // AND CHECK FOR SPECIAL CHARACTER
) {
return false;
}
return true;
}
var_dump( encPasswordCheckFailed("abcd123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD1#23-") ); //<== boolean false
The dash/minus character is your issue, as when inside a character group, it denotes a character range.
You need to either:
Escape it with a backslash, so that it isn't treated as a special character:
/[!##$%^&*()\-+<>]+/
Or put it at the end of the pattern, so the PCRE engine knows it can't possibly denote a range:
/[!##$%^&*()+<>-]+/
Similarly, the caret (^) is also a special character, denoting negation when inside a character group, but because you didn't put it at the very first position inside the character group, the PCRE engine knows it has no special meaning in your case.
This will gonna work for special characters:
preg_match('/\[!##$%^&*\(\)\-+<>\]+/', $password);
If it's not working, look down:
OTHER ANSWERS:
preg_match php special characters (pmm's answer)
Related
I am trying to validate if a new user account's password is matching these criterias:
Between 8-30 characters long
Contains at least 1 lowercase letter (a-z)
Contains at least 1 uppercase letter (A-Z)
Contains at least 1 of the following special characters: _-!#*#&
I have a function like this:
function validPassword($str) {
return preg_match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_-!#*#&])[A-Za-z\d_-!#*#&]{8,30}$", $str);
}
But I am getting an error. It should return "true" for this password for example: HelloWorld123!
But instead it is returning false. Any idea what may be wrong?
if (validPassword($password) == true) {
// good password
}
You forgot to escape '-', and delimiters...
function validPassword($str) {
return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$/", $str);
}
Your regex is having errors which is why there is no match in the first place.
Change your regex to this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$
Have a look at your regex in action here: https://regex101.com/r/ogPPeb/1
I wish to validate user input based on the following requirements:
Must be alphanumeric
Longer or equal to five characters
I have succeded with the above but two of my other requirements remains:
Must have UTF8 characters åäöÅÄÖ
Must allow dot and slash
if(!(preg_match('/^\w{5,}$/', $username))) { return true; }
Can anyone help me extend this expression for my requirements?
Use unicode propeties:
if(!(preg_match('~^[\pL\pN./]{5,}$~u', $username))) { return true; }
\pL stands for any letter
\pN stands for any number.
Try this:
if(!(preg_match('/^[\w.\/]{5,}$/u', $username))) { return true; }
if(!(preg_match('/^[a-zA-Z0-9.\/]{5,}$/', $username))) { return true; }
I have a set of characters that are allowed in a string of text. Is it possible to use preg_match to detect the existence of characters outside of the range of provided characters?
for example:
$str1 = "abcdf9"
$str2 = "abcdf#"
$str3 = "abcdfg"
legal chars = "a-z"
if (preg_match() ... ) needs to return false for '$str1' & '$str2', but 'tru' for $str3.
Will this be possible?
if(!preg_match('/[^a-z]/', $string)) { //only a-z found }
//or
if(preg_match('/[^a-z]/', $string)) {
return false; // other stuff found
} else {
return true; // only a-z found
}
See this site very usefull to deploy your regEx
http://regexr.com/
What do you need is /[a-z]/ ?
You can specify the number of chars with /[a-z]{5}/
I have a reg exp which is supposed to check if there are any illegal characters in a name. THe allowed characters are 0-9, a-z, A-Z, middlescore(-) and underscore( _ ).
This is the function
function validate_playername($playername){
if (preg_match('/^[0-9A-Z-_]$/i',$playername)) {
return true;
} else{
return false;
}
}
the function is called like this
if (validate_playername($addplayer)) {
echo "valid player Name";
} else {
echo "Invalid Player Name";
}
However when I enter a correct name like velocity28 it returns as an Invalid player name. Is my reg exp wrong?
/^[0-9A-Z-_]$/i matches only one character.
Append + to match multiple characters:
'/^[-0-9A-Z_]+$/i'
moved - to the beginning.
UPDATE
As Enissay commented, the regular expression can be simplified using \w:
'/^[-\w]+$/'
To use a literal minus sign in a character class, it must be escaped with a backslash:
function validate_playername($playername){
if (preg_match('/^[0-9A-Z\-_]$/i',$playername)) {
return true;
} else{
return false;
}
}
See http://php.net/manual/de/regexp.reference.character-classes.php for further information.
You could also move the minus sign to a position where it can't be part of character range definition, e.g. make it the first character in the character class.
I am writing a PHP validation for a user registration form. I have a function set up to validate a username which uses perl-compatible regular expressions. How can I edit it so that one of the requirements of the regular expression are AT MOST a single . or _ character, but NOT allow that character at the beginning or end of the string? So for example, things like "abc.d", "nicholas_smith", and "20z.e" would be valid, but things like "abcd.", "a_b.C", and "_nicholassmith" would all be invalid.
This is what I currently have but it does not add in the requirements about . and _ characters.
function isUsernameValid()
{
if(preg_match("/^[A-Za-z0-9_\.]*(?=.{5,20}).*$/", $this->username))
{
return true; //Username is valid format
}
return false;
}
Thank you for any help you may bring.
if (preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
// there is at most one . or _, and it's not at the beginning or end
}
You can combine this with the string length check:
function isUsernameValid() {
$length = strlen($this->username);
if (5 <= $length && $length <= 20
&& preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
return true;
}
return false;
}
You could probably do the whole lot using just one regex, but it would be much harder to read.
You can use the following pattern, I have divided it into multiple lines to make it more understandable:
$pattern = "";
$pattern.= "%"; // Start pattern
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "[\\._]"; // Contains exactly either one "_" or one "."
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "%i"; // End pattern, optionally case-insensetive
And then you can use this pattern in your function/method:
function isUsernameValid() {
// $pattern is defined here
return preg_match($pattern, $this->username) > 0;
}
Here is a commented, tested regex which enforces the additional (unspecified but implied) length requirement of from 5 to 20 chars max:
function isUsernameValid($username) {
if (preg_match('/ # Validate User Registration.
^ # Anchor to start of string.
(?=[a-z0-9]+(?:[._][a-z0-9]+)?\z) # One inner dot or underscore max.
[a-z0-9._]{5,20} # Match from 5 to 20 valid chars.
\z # Anchor to end of string.
/ix', $username)) {
return true;
}
return false;
}
Note: No need to escape the dot inside the character class.