Denis Šišić Denis Šišić - 2 years ago 72
PHP Question

Unique regex for name validation

I want to check is the name valid with regex PHP, but i need a unique regex that allows:

  • Letters (upper and lowercase)

  • Spaces (max 2)

But there can't be a space after space..
For example:
Name -> Dennis Unge Shishic (valid)
Name -> Denis(space)(space) (not valid)

Hope you guys understand me, thank you :)

Answer Source

First, it's worth mentioning that having such restrictive rules for the names of persons is a very bad idea. However, if you must, a simple character class like this will limit you to just uppercase and lowercase English letters:


To match one or more, you need to add a + after it. So, this will match the first part of the name:


To capture a second name, you just need to do the same thing preceded by a space, so something like this will capture two names:

[A-Za-z]+ [A-Za-z]+

To make the second name optional, you need to surround it by parentheses and add a ? after it, like this:

[A-Za-z]+( [A-Za-z]+)?

And to add a third name, you just need to do it again:

[A-Za-z]+( [A-Za-z]+)? [A-Za-z]+

Or, you could specify that the latter names can repeat between 1 and 2 times, like this:

[A-Za-z]+( [A-Za-z]+){1,2}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download