开发者

PHP regex to check a English name

开发者 https://www.devze.com 2023-01-14 17:36 出处:网络
Looking for a regex to check a valid English name, i.e.: A-Z, a-z, space only First name,(optional) Middle name, Last name

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

  • A-Z, a-z, space only
  • First name, (optional) Middle name, Last name

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, 'Fi开发者_开发技巧rst Middle Last Fourth');
    echo check_name($regex, 'First 123');

?>


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).


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}/


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!!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号