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.
Related
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)
I am checking username entered by user
I'm trying to validate usernames in PHP using preg_match() but I can't seem to get it working the way I want it. I require preg_match() to:
accept only letters , numbers and . - _
i.e. alphanumeric dot dash and underscore only, i tried regex from htaccess which is like this
([A-Za-z0-9.-_]+)
like this way but it doesnt seem to work, it giving false for simple alpha username.
$text = 'username';
if (preg_match('/^[A-Za-z0-9.-_]$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
How can i make it work ?
i am going to use it in function like this
//check if username is valid
function isValidUsername($str) {
return preg_match('/[^A-Za-z0-9.-_]/', $str);
}
i tried answwer in preg_match() and username but still something is wrong in the regex.
update
I am using code given by xdazz inside function like this.
//check if username is valid
function isValidUsername($str) {
if (preg_match('/^[A-Za-z0-9._-]+$/' , $str)) {
return true;
} else {
return false;
}
}
and checking it like
$text = 'username._-546_546AAA';
if (isValidUsername($text) === true) {
echo 'good';
}
else{
echo 'bad';
}
You missed the +(+ for one or more, * for zero or more), or your regex only matches a string with one char.
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
hyphen - has special meaning inside [...] that is used for range.
It should be in the beginning or in the last or escape it like ([A-Za-z0-9._-]+) otherwise it will match all the character that is in between . and _ in ASCII character set.
Read similar post Including a hyphen in a regex character bracket?
Better use \w that matches [A-Za-z0-9_]. In shorter form use [\w.-]+
What is the meaning for your last regex pattern?
Here [^..] is used for negation character set. If you uses it outside the ^[...] then it represents the start of the line/string.
[^A-Za-z0-9.-_] any character except:
'A' to 'Z',
'a' to 'z',
'0' to '9',
'.' to '_'
Just put - at the last in character class and add + after the char class to match one or more characters.
$text = 'username';
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
function should be like this
function isValidUsername($str) {
return preg_match("/^[A-Za-z0-9._-]+$/", $str);
}
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 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.