full name regex

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
phper
Forum Newbie
Posts: 1
Joined: Mon Jan 19, 2009 10:38 am

full name regex

Post by phper »

I just spent a few hours on this and it is driving me nuts. I just cannot get it to work. I googled and searched these forum and I am just going around in circles.

I need to do a regex on a name field using PHP. The name could be any combination of names

- John Doe
- John O'Doe
- John O' Doe
- John & Mary Doe
- John & Mary O' Doe
- John Doe-Schmoe
etc...
or of course, any combination of the above.

Here is what I tried so far:

Code: Select all

 
 
// doesn't work
if (!preg_match("/[^\w\s]/i",$name)) { 
    $this->setError('NoName');
} 
 
// doesn't work 
if (!preg_match("/[a-zA-Z -\'&]*[\s]+[a-zA-Z -\'&]*/i",$name)) { 
    $this->setError('NoName');
} 
 
// doesn't work 
if (preg_match("/([[:digit:]]|[~`!@#$%^*()_=+{}|\:;"/?,]|[|]|-)+//i",$name)) { 
    $this->setError('NoName');
} 
 
Can anyone shed any light on this.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: full name regex

Post by prometheuzz »

I don't know why you'd want such "precise" validation instead of just checking if something has been entered, but this regex:

Code: Select all

$regex = "/^([&'\s]*[A-Z]\S+)+$/";
will match all your input examples.
Post Reply