Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mikegk's avatar

Regex for username

Hey guys,

I'm really not that great when it comes to regex. However, I need a regular expression to ensure, a username matches a given pattern. Allowed are: 0-9, a-Z, öÖ äÄ üÜ ß, one whitespace/ space between two character but none at the beginning and none at the end, "-" signs also not at the beginning and the end but between characters.

Right now, this is what I made:

return Validator::make($data, [
            'user' => ['required', 'string', 'max:100', 'unique:user','regex'=>'^[0-9a-zA-Z-öÖäÄüÜ ]*'],
        ]);

Regex can be found here: https://www.phpliveregex.com/p/FHE

Would be so happy for any help 🙏🏻

0 likes
4 replies
Snapey's avatar

perhaps ^[0-9a-zA-Z\-öÖäÄüÜ\s]*

I would not worry about space at either end as it can be trimmed ( if not done already)

1 like
kokoshneta's avatar

So let me check if I’ve understood your requirements correctly. You would accept adüxß-spWq29 dOs02 as a user name, but these should all be rejected (using interpuncts ‘•’ to represent spaces, which are invisible otherwise):

  • •adüxß-spWq29•dOs02 (starts with space)
  • adüxß-spWq29••dOs02 (double space between words)
  • -adüxß-spWq29•dOs02 (starts with hyphen)
  • (?) adüxß--spWq29•dOs02 (double hyphen between words)

Is that right? (And why are underscores not allowed? They’re very common in user names.)

Assuming you don’t want to allow -- in user names, this should do it (PHPLiveRegex):

'regex' => '^(?:[0-9a-zA-ZäÄöÖüÜß]+[ -]?)+[0-9a-zA-ZäÄöÖüÜß]$'

If you do need to allow multiple consecutive hyphens, this should do it instead:

'regex' => '^(?:[0-9a-zA-ZäÄöÖüÜß]+(?: |-*)?)+[0-9a-zA-ZäÄöÖüÜß]$'
1 like
Mikegk's avatar

@kokoshneta your answer was a great help, thank you. Is it possible to extend this regex so that it will not allow strings that just consist of numbers (like: 12345, 49385, and so on). Your regular expression is sadly far beyond my regex "skills", so I wasn't able to fix that using the LiveRegex tool.

kokoshneta's avatar
Level 27

@Mikegk I don’t think that can be done in a single regex offhand – at least not in a way I can think of.

But you can use not-regex to add a negative constraint to the existing positive constraint:

return Validator::make($data, [
	'user' => [
		'required',
		'string',
		'max:100',
		'unique:user',
		'regex' => '^(?:[0-9a-zA-ZäÄöÖüÜß]+(?: |-*)?)+[0-9a-zA-ZäÄöÖüÜß]$',
		'not_regex' => '^\d+$'
	]
]);
1 like

Please or to participate in this conversation.