vgkuttu
vgkuttu

Reputation: 7

Match a string prefix in PHP

I have a username of the format, say: "mySite", with a number suffixed to it.

I need to check whether the entered username matches that format.

I match strings using preg_match as follows:

if(!(preg_match("/^[mySite]([0-9])+$/", $loginName)))

    echo "Error";

But, I don't get the desired results.

Is the above expression correct?

Upvotes: 0

Views: 1425

Answers (3)

mpen
mpen

Reputation: 283103

no. try

preg_match('/^mySite\d+$/', $loginName)

[mySite] will match any of the letters m,y,S,i,t,e. and only one of them.

Upvotes: 2

Joey
Joey

Reputation: 354734

Remove the brackets around mySite. Otherwise you're just matching a single character with it that is either m, y, S, i, t or e.

Upvotes: 1

xiaowl
xiaowl

Reputation: 5217

This should work:

if(!(preg_match("/^mySite([0-9])+$/", $loginName)))

    echo "Error";

Upvotes: 1

Related Questions