PHP正则表达式只接受字母和数字,只接受一个点

I don't know much about regex and I'm trying to create a username string accepts only English letters and numbers and only one dot.

I have this regex code:

if(preg_match('/[^A-Za-z0-9]/', $username)){
    $error = "Invalid Username";
}

this code allowed me to have only English letters and number, I want to add dots to this code, and accept only one dot.

Only one dot, but anywhere in the string? I'd make that a second check:

if(preg_match('/[^A-Za-z0-9\.]/', $username) || substr_count($username, '.') > 1){
    $error = "Invalid Username";
}

You need to apply a lookahead assertion in order to confirm it:

if (preg_match('/^(?!(?>[^.]*\.){2})[A-Za-z0-9\.]+$/', $username)) {
    // username accepted
}

preg_match approach:

$error = '';
if (!preg_match('/^(\.[a-z0-9]+|[a-z0-9]+\.([a-z0-9]*))$/i', $username)) {
    $error = "Invalid Username";
}

if ($error) echo $error;

You may use

if (!preg_match('~^[A-Z0-9]*(?:\.[A-Z0-9]*)?$~i', $username))
{
     $error = "Invalid Username";
}

See the PHP demo and a regex demo. The [A-Z0-9] can be replaced with [[:alnum:]] to match letters or digits.

Details

  • ^ - start of string
  • [A-Z0-9]* - 0 or more letters or digits
  • (?: - start of an optional non-capturing group
    • \. - a dot
    • [A-Z0-9]* - 0 or more letters or digits
  • )? - end of the optional group
  • $ - end of string.

This case could be handled very easy by just repeating the pattern around the optional dot.

`^[A-Za-z0-9]*\.?[A-Za-z0-9]*$`

wrapped up in php

if (!preg_match('`^[A-Za-z0-9]*\.?[A-Za-z0-9]*$`', $username)) {
    $error = "Invalid username";
}