Page 1 of 1

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

Posted: Tue Aug 31, 2021 4:41 pm
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 ]+$/

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

Posted: Wed Sep 01, 2021 7:29 pm
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,}

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

Posted: Thu Sep 02, 2021 3:25 am
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

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

Posted: Thu Sep 02, 2021 11:45 am
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,}

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

Posted: Sat Sep 04, 2021 7:00 am
by cjkeane
Great that worked thank you.