ohho
ohho

Reputation: 51951

PHP regex to check a English name

Looking for a regex to check a valid English name, i.e.:

An acceptable example: John von Neumann

Thanks!

EDIT (added checking code):

#!/usr/bin/php

<?php

    function check_name($regex, $name)
    {
        $rc = 'Bad';
        if (preg_match($regex, $name)) {    
            $rc = 'Good';
        }
        return '|' . $name . '| ' . $rc . "\n";
    }

    $regex = '/(?:[A-Za-z]+(?:\s+|$)){2,3}/';
    echo check_name($regex, 'First');
    echo check_name($regex, 'First Last');
    echo check_name($regex, 'Two  Spaces');
    echo check_name($regex, 'First Middle Last');
    echo check_name($regex, 'First Middle Last Fourth');
    echo check_name($regex, 'First 123');

?>

Upvotes: 1

Views: 4809

Answers (4)

Amber
Amber

Reputation: 527548

If the rules you've stated are actually what you want, the following would work:

/^(?:[A-Za-z]+(?:\s+|$)){2,3}$/

However, there are quite a few real-life names that don't fit in these rules, like "O'Malley", "Jo-Jo", etc.

You can of course extend this regex fairly easily to allow other characters - just add them into the brackets. For instance, to allow apostrophes and dashes, you could use [A-Za-z'-] (the - has to be at the end, or it will be interpreted as a range).

Upvotes: 7

Adam Crume
Adam Crume

Reputation: 15844

This is a bad idea. People may have various punctuation characters in their names, such as dashes and apostrophes. They may also have accented or foreign letters. Also, the number of middle names can vary greatly.

Upvotes: 0

Theodore R. Smith
Theodore R. Smith

Reputation: 23259

Your name is going to fail for the O'Neil's out there. Also the Webb-Smiths and the like.

Use @Amber's modified:

/(?:[A-Za-z.'-]+\s*){2,3}/

Upvotes: 2

codaddict
codaddict

Reputation: 455470

You can try:

if(preg_match('/^([a-z]+ ){1,2}[a-z]+$/i',trim($input))) {
  // valid full name.
}

As noted by others, it will allow NO punctuations in the name!!

Upvotes: 0

Related Questions