PHP preg_match() must have first and last name with a space between

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

PHP preg_match() must have first and last name with a space between

Post by cjkeane »

Hi everyone,

I am trying to create a preg_match() to allow a full name to be entered, and it must contain a space between both words. I have tried the preg_match() expressions below. They permit spaces in the name, but a space is not mandatory. Are there any hints on how to make sure there is a space between both words. Thanks.

/^[a-zA-Z ]+$/
/^[A-Z][a-zA-Z ]+$/
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP preg_match() must have first and last name with a space between

Post by Benjamin »

Without any examples I'm guessing here.

Does this work for you? It matches "firstname lastname"

Code: Select all

[a-zA-Z]{0,}\s{0,}[a-zA-Z]{0,}
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP preg_match() must have first and last name with a space between

Post by cjkeane »

Thank you for responding! That might work but what does {0,} do? Does that indicate that a space must be between both names?

Here are some examples. Basically, just a proper given name should only be allowed.

JohnSmith — won’t be allowed
John Smith — will be allowed
John - will not be allowed
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP preg_match() must have first and last name with a space between

Post by Benjamin »

It should be set to the minimum length of the first and last name you want to match. It means X or more times. \s{1,} forces there to be a space between the words.

So you may want to change it to something such as:

Code: Select all

[a-zA-Z]{2,}\s{1,}[a-zA-Z]{2,}
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP preg_match() must have first and last name with a space between

Post by cjkeane »

Great that worked thank you.
Post Reply