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';
}

      

+3


source to share


4 answers


Are you missing +

( +

for one or more, *

for zero or more), or your regex matches a string with one char.



if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
   echo 'true';   
} else {
   echo 'false';
}

      

+2


source


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 '_'

      

+2


source


Just put -

in the last character class and add +

char after the class to match one or more characters.

$text = 'username';

if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
   echo 'true';   
} else {
   echo 'false';
}

      

+1


source


Function

should be like this

function isValidUsername($str) {
    return preg_match("/^[A-Za-z0-9._-]+$/", $str);
}

      

+1


source







All Articles