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