What would be a regex to check for alphanumeric dot barcode and underscore using preg_match?
I check the username entered by the user
I'm trying to check usernames in PHP using preg_match (), but I can't seem to get it to work the way I want it to. I require preg_match ():
- accept only letters, numbers, etc. - _
those. alphanumeric dot label and underscore only, I tried regex from htaccess which is like this
([A-Za-z0-9.-_]+)
like this way but it doesn't seem to work, it gives false information for simple alpha username.
$text = 'username';
if (preg_match('/^[A-Za-z0-9.-_]$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
How can I get it to work?
I am going to use it in a 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 there is still something wrong with the regex.
Refresh
I use the code given by the xdazz function inside such a function.
//check if username is valid
function isValidUsername($str) {
if (preg_match('/^[A-Za-z0-9._-]+$/' , $str)) {
return true;
} else {
return false;
}
}
and check it like
$text = 'username._-546_546AAA';
if (isValidUsername($text) === true) {
echo 'good';
}
else{
echo 'bad';
}
source to share
defen -
has a special meaning internally [...]
that is used for the range.
It must be at the beginning or at the end, or print it like ([A-Za-z0-9._-]+)
, otherwise it will match all characters between .
and _
in the ASCII character set.
Read a similar message Include a hyphen in a regular expression parenthesis?
It is better to use \w
which is appropriate [A-Za-z0-9_]
. In a shorter form, use[\w.-]+
What is the point of your latest regex pattern?
[^..]
Used here to set negation characters. If you use it outside ^[...]
, then it represents the beginning of a line / line.
[^A-Za-z0-9.-_] any character except:
'A' to 'Z',
'a' to 'z',
'0' to '9',
'.' to '_'
source to share