FR STAR
FR STAR

Reputation: 702

PHP preg_match is not working properly

My client ask me to add new a rule to the username to his website login. Therefore I've tried the following code.

  $userid = "12345678SM"; //format of the username
  $check="/^[0-9]+[S].[M]{10}$/i";
  $check2="/^[0-9]+[F].[M]{10}$/i";
    print($name);
  if(!preg_match($check,$userid) || !preg_match($check2,$userid)) {
    print('The user id is invalid');                    
  }

However, even though I entered the correct format of the username it's printing the error. I've actually used this code sometimes ago and worked but here I don't understand why it's not working. Could anyone please help me out of this ?

FYI: Format of the username should be 7 digits and 2 selected alphabet characters eg: SM or FM

Upvotes: 0

Views: 187

Answers (2)

Pixus.ru
Pixus.ru

Reputation: 106

The "[M]{10}" part matches "MMMMMMMMMM". The format you described could be checked with

^[0-9]{8}[S|F]M$

Also you said

$userid = "12345678SM"; (8 digits)

but

Format of the username should be 7 digits and 2 selected alphabet characters

My example will work for 8.

Upvotes: 1

baloo
baloo

Reputation: 7765

[M]{10} means that 10 M is required.

The correct check would be:

$check="/^\d{7}[SF]M$/i";
if (!preg_match($check, $userid)) {
    print('The user id is invalid');                    
}

Upvotes: 3

Related Questions