用PHP将用户名与正则表达式进行比较

I've never used regular expressions before and did some research on how to allow my username field only alphanumeric characters, dashes, dots, and underscores. I have the following expression but it doesn't seem to be working.

$string = "Joe_Scotto";

if (!preg_match('[a-zA-Z0-9_-.]', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

I want the statement to return true if it is following the "guidelines" and false if the username contains something other than what I specified it should contain. Any help would be great. Thanks!

Try this

$string = "Joe_Scotto";

if (!preg_match('/^[A-Za-z0-9_.]+$/', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

You match only a single character. Try this:

$string = "Joe_Scotto";

if (!preg_match('/^[a-zA-Z0-9_.-]+$/', $string)) {
    echo "Does not match Regex";
} else {
    echo "Matches";
}

The + sign says: match 1 or more characters defined directly before the + (* is the same but matches 0 or more characters). Also the separators '/' (or any other separator characters) are required. And in character classes, it is better to place the - sign to the end, else it could be misinterpreted as range from _ to . And add ^ at the beginning (this means: match from the beginning of the input) and $ to the end (this means: match to the end of the input). Else, also a part of the string would match.

You should use something like that http://www.phpliveregex.com/p/ern

$string = 'John_Buss';

if (preg_match('/[A-z0-9_\-.]+/', $string)) {
    return true;
} else {
    return false;
}

Make sure to add / delimiter character at the start and the end of your regex

Make sure to use \ escape character before -

Make sure to add + character quantifier