Regex - Return First and Last Name

前端 未结 7 1164
一整个雨季
一整个雨季 2021-01-15 08:51

I\'m looking for the best reliable way to return the first and last name of a person given the full name, so far the best I could think of is the following

7条回答
  •  Happy的楠姐
    2021-01-15 09:08

    As is, you're requiring a last name -- which, of course, your first example doesn't have.

    Use clustered grouping, (?:...), and 0-or-1 count, ?, for the middle and last names as a whole to allow them to be optional:

    '~\b(\p{L}+)\b (?: .+\b(\p{L}+)\b )?~ix'  # x for spacing
    

    This should allow the first name to be captured whether middle/last names are given or not.

    $name = preg_replace('~\b(\p{L}+)\b(?:.+\b(\p{L}+)\b)?~i', '$1 $2', $name);
    

提交回复
热议问题