Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to split a first and last name in PHP

Tags:

php

I am stuck with a NAME field, which typically is in the format:

FirstName LastName

However, I also have the occasional names that are in any of these formats (with prefix or suffix):

Mr. First Last
First Last Jr.

What do people think is a safe way to split these into FIRST/LAST name variables in PHP? I can't really come up with anything that tends to work all of the time...

like image 295
Shackrock Avatar asked Jan 10 '12 18:01

Shackrock


1 Answers

A regex is the best way to handle something like this. Try this piece - it pulls out the prefix, first name, last name and suffix:

$array = array(
    'FirstName LastName',
    'Mr. First Last',
    'First Last Jr.',
    'Shaqueal O’neal',
    'D’angelo Hall',
);

foreach ($array as $name)
{
    $results = array();
    echo $name;
    preg_match('#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results);
print_r($results);
}

The result comes out like this:

FirstName LastName
Array
(
    [0] => FirstName LastName
    [1] => 
    [2] => FirstName
    [3] => LastName
)
Mr. First Last
Array
(
    [0] => Mr. First Last
    [1] => Mr.
    [2] => First
    [3] => Last
)
First Last Jr.
Array
(
    [0] => First Last Jr.
    [1] => 
    [2] => First
    [3] => Last
    [4] => Jr.
)
shaqueal o’neal
Array
(
    [0] => shaqueal o’neal
    [1] => 
    [2] => shaqueal
    [3] => o’neal
)
d’angelo hall
Array
(
    [0] => d’angelo hall
    [1] => 
    [2] => d’angelo
    [3] => hall
)

etc…

so in the array $array[0] contains the entire string. $array[2] is always first name and $array[3] is always last name. $array[1] is prefix and $array[4] (not always set) is suffix. I also added code to handle both ' and ’ for names like Shaqueal O’neal and D’angelo Hall.

like image 183
Francis Lewis Avatar answered Sep 29 '22 16:09

Francis Lewis