How can you tell if a string has only a username and not any other text (e.g. "@username" OR "@username " RATHER THAN "@username text")
- 2,480
- 6
- 18
- 25
- 76
- 1
- 6
-
2Personally, for usernames I'd use a regular expression that limits user input to only certain allowed characters. – rickdenhaan Jan 15 '18 at 22:23
1 Answers
Use a regular expression that looks for @[A-Za-z]+
That'll just match letters... if you need to allow numbers and underscores, you'll need something like @[A-Za-z0-9_]+.
To allow zero or more trailing whitespace characters you can add \s*
Wrap in ^ and $ to match the start and end of the string.
Here's the whole regex:
@[A-Za-z0-9_]+\s*
If you need more matchable characters you can add them into the brackets. You may need to escape dash (-) as \- depending where you put it.
If you need just A-Za-z0-9_ then you can shortcut that as \w if you like. Here's the short version:
@\w+\s*
Aside: if you are here from ruby for some reason - be careful with ^ and $ - you should "probably" be using \A and \z instead (see Difference between \A \z and ^ $ in Ruby regular expressions )
- 1,349
- 13
- 20
-
-
2@ThomasGeorge You can use `if (preg_match('/^@\w+\s*$/', $username) === 1) {/* username is correct */} else {/* username is incorrect */}` – Philipp Maurer Jan 16 '18 at 09:08