Instagram username Regex -PHP
Moving forward from the comment section, this is what you want:
if(!empty($instaUsername) && preg_match('/^[a-zA-Z0-9._]+$/', $instaUsername)) {
throw new Exception ("Your name Instagram is incorrect");
}
This regex should work for you:
~^([a-z0-9._])+$~i
You can use anchors to match the start (^
) and the end $
of your input. And use the modifier i
for case-insensitivity.
jstassen has a good write up on insta user names:
(?:^|[^\w])(?:@)([A-Za-z0-9_](?:(?:[A-Za-z0-9_]|(?:\.(?!\.))){0,28}(?:[A-Za-z0-9_]))?)
Thus you want a regex what validates Instagram usernames? Well then, shall we first do some research on what the requirements actually are? Okay let's start!
...
Well it seems like Instagram doesn't really speak out about the requirements of a valid username. So I made an account and checked what usernames it accepts and what usernames are rejected to get a sense of the requirements. The requirements I found are as following:
- The length must be between 3 and 30 characters.
- The accepted characters are like you said:
a-z A-Z 0-9 dot(.) underline(_)
. - It's not allowed to have two or more consecutive dots in a row.
- It's not allowed to start or end the username with a dot.
Putting all of that together will result in the following regex:
^[\w](?!.*?\.{2})[\w.]{1,28}[\w]$
Try it out here with examples!