65

I'm developing a private message system that allows users to search for a user by their full name, e.g.: "George Washington".

I have two variables named $firstname and $lastname, and the search function orders results by relevancy (how many times you have messaged that person). How do I get a text field to split "George Washington" into $firstname="George" and $lastname="Washington"?

19 Answers 19

131

The simplest way is, by using explode:

$parts = explode(" ", $name);

After you have the parts, pop the last one as $lastname:

$lastname = array_pop($parts);

Finally, implode back the rest of the array as your $firstname:

$firstname = implode(" ", $parts);

example:

$name = "aaa bbb ccc ddd";

$parts = explode(" ", $name);
if(count($parts) > 1) {
    $lastname = array_pop($parts);
    $firstname = implode(" ", $parts);
}
else
{
    $firstname = $name;
    $lastname = " ";
}

echo "Lastname: $lastname\n";
echo "Firstname: $firstname\n";

Would result:

tomatech:~ ariefbayu$ php ~/Documents/temp/test.php 
Lastname: ddd
Firstname: aaa bbb ccc
8
  • For this to work, the array_pop statement is necessary. For example, if you just needed the first name.
    – dr_rk
    Jun 21, 2016 at 11:43
  • Another conditional statement if the name doesn't have a space, you may want to if (count($parts) == 1) {$firstname = $name;$lastname = ''} Oct 11, 2016 at 16:07
  • 2
    so you will have to change the code as $parts = explode(" ", $name); if(count($parts) > 1) { $lastname = array_pop($parts); $firstname = implode(" ", $parts); } else { $firstname = $name; $lastname = " "; } Jan 4, 2017 at 9:27
  • 1
    wont work in South Africa where you have last names like "Van Den Berg" or "Van Deventer" or "Van Der Merwe" Jan 30, 2019 at 10:22
  • 1
    @ChristopherSmit If you do not have middle names, if you have two parts lastnames, use array_shift() to catch firstname. $firstname = array_shift($parts); $lastname = implode(" ", $parts); see: https://phpfiddle.tk/6e0e5595 Aug 31, 2019 at 11:55
93

I like cballou's answer because there's an effort to check if there's only a first name. I thought I'd add my functions for anyone else who comes lookin'.

Simple Function, Using Regex (word char and hyphens)

  • It makes the assumption the last name will be a single word.
  • Makes no assumption about middle names, that all just gets grouped into first name.
  • You could use it again, on the "first name" result to get the first and middle though.

Here's the code:

// uses regex that accepts any word character or hyphen in last name
function split_name($name) {
    $name = trim($name);
    $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
    $first_name = trim( preg_replace('#'.preg_quote($last_name,'#').'#', '', $name ) );
    return array($first_name, $last_name);
}

Ex 1: split_name('Angeler') outputs:

array(
    0 => 'Angeler',
    1 => ''
);

Ex 2: split_name('Angeler Mcgee') outputs:

array(
    0 => 'Angeler',
    1 => 'Mcgee'
);

Ex 3: split_name('Angeler Sherlee Mcgee') outputs:

array(
    0 => 'Angeler Sherlee',
    1 => 'Mcgee'
);

To get the first and middle name split,

Ex 4: split_name('Angeler Sherlee') outputs:

array(
    0 => 'Angeler',
    1 => 'Sherlee'
);

Another Function - Detects Middle Names Too

Later I decided that it would be nice to have the middle name figured out automatically, if applicable, so I wrote this function.

function split_name($name) {
    $parts = array();

    while ( strlen( trim($name)) > 0 ) {
        $name = trim($name);
        $string = preg_replace('#.*\s([\w-]*)$#', '$1', $name);
        $parts[] = $string;
        $name = trim( preg_replace('#'.preg_quote($string,'#').'#', '', $name ) );
    }

    if (empty($parts)) {
        return false;
    }

    $parts = array_reverse($parts);
    $name = array();
    $name['first_name'] = $parts[0];
    $name['middle_name'] = (isset($parts[2])) ? $parts[1] : '';
    $name['last_name'] = (isset($parts[2])) ? $parts[2] : ( isset($parts[1]) ? $parts[1] : '');
    
    return $name;
}

Ex 1: split_name('Angeler Sherlee Mcgee') outputs:

array(
    'first_name' => 'Angeler',
    'middle_name' => 'Sherlee',
    'last_name' => 'Mcgee'
);

Ex 2: split_name('Angeler Mcgee') outputs:

array(
    'first_name' => 'Angeler',
    'middle_name' => '',
    'last_name' => 'Mcgee'
);

Another Way - Sans Regex

Decided to add another way that doesn't use regex.

It also has return false; for non-recognizable names (null, empty string, too many word groups to infer).

<?php

function split_name($string) {
    $arr = explode(' ', $string);
    $num = count($arr);
    $first_name = $middle_name = $last_name = null;
    
    if ($num == 2) {
        list($first_name, $last_name) = $arr;
    } else {
        list($first_name, $middle_name, $last_name) = $arr;
    }

    return (empty($first_name) || $num > 3) ? false : compact(
        'first_name', 'middle_name', 'last_name'
    );
}

var_dump(split_name('Angela Mcgee'));
var_dump(split_name('Angela Bob Mcgee'));
var_dump(split_name('Angela'));
var_dump(split_name(''));
var_dump(split_name(null));
var_dump(split_name('Too Many Names In Here'));

Outputs

Array
(
    [first_name] => Angela
    [middle_name] => NULL
    [last_name] => Mcgee
)

Array
(
    [first_name] => Angela
    [middle_name] => Bob
    [last_name] => Mcgee
)

Array
(
    [first_name] => Angela
    [middle_name] => NULL
    [last_name] => NULL
)

false

false

false
11
  • That would fall into the "too many names in here" example above. You can modify the function to accommodate for more naming situations... Also a good suggestion is to store a name in your database as one singular name, and just pop off the first part for display things like "Hi XXXX," as needed.
    – amurrell
    Aug 17, 2018 at 22:59
  • 2
    The regex works great for me but I would add a single quote to it as well to catch the O'Briens and O'Malleys, etc. #.*\s([\w-']*)$#
    – mlerley
    Feb 25, 2019 at 17:31
  • To make this work so all suffixes were simply added to the last name, I added an elseif. ``` else if ($num > 3) { list($first_name, $middle_name, $last_name) = $arr; for($i = 3; $i <= $num; $i++) { $last_name = $last_name . " " . $arr[$i]; }
    – CosetteN
    Mar 25, 2019 at 21:46
  • If for some reason the first name contains the last name, that also gets removed from the first name. Jul 12, 2019 at 14:58
  • 1
    @Jnanaranjan Which one of these methods did not work? The sans-regex one? You can always expand upon / adapt these solutions to fit your unique case. Can you be more specific with which method you were using that did not work?
    – amurrell
    Nov 14, 2019 at 20:53
28

if you have exactly 2-word input you can use list()

list($firstname, $lastname) = explode(" ", $string);

anyway you can use explode()

$words = explode(" ", $string);

$firstname = $words[0];
$lastname = $words[1];
$third_word = $words[2];
// ..
18

In my situation, I just needed a simple way to get first and last, but account for basic middle names:

$parts = explode(' ', 'Billy Bobby Johnson'); // $meta->post_title
$name_first = array_shift($parts);
$name_last = array_pop($parts);
$name_middle = trim(implode(' ', $parts));

echo 'First: ' . $name_first . ', ';
echo 'Last: ' . $name_last . ', ';
echo 'Middle: ' . $name_middle . '.';

Output:

First: Billy, Last: Johnson, Middle: Bobby.

1
  • 1
    This is the best. Caters for first, middle and last name like a boss
    – mutiemule
    Jul 14, 2017 at 11:24
9
list($firstname, $lastname) = explode(' ', $fullname,2);
4
  • 1
    vlcekmi3 beat you to it 3 years earlier.
    – miken32
    May 23, 2016 at 23:22
  • 3
    @miken32: My answer is not same to his. Check carefully.
    – Sultan
    May 24, 2016 at 9:30
  • Despite it's low number of upvotes, it is a very clever one May 31, 2016 at 14:17
  • Sultan is correct, vlcekmi3's answer didn't include a limit which will fail for names with the middle name or unique multi-word last names.
    – dave
    Sep 14, 2018 at 6:06
7

http://php.net/manual/en/function.explode.php

$string = "George Washington";
$name = explode(" ", $string);
echo $name[0]; // George 
echo $name[1]; // Washington
1
  • 1
    In theory good idea but if your name is "Jose De La Souza Martinez" then this would only produce "Jose De". May 12, 2016 at 6:59
6

Here's an answer with some bounds checking.

While the answers above are correct, they don't provide any form of bounds condition checks to ensure you actually have a valid name to begin with. You could go about this with a strpos() check to see if a space exists. Here's a more thorough example:

function split_name($name)
{
    $name = trim($name);
    if (strpos($name, ' ') === false) {
        // you can return the firstname with no last name
        return array('firstname' => $name, 'lastname' => '');

        // or you could also throw an exception
        throw Exception('Invalid name specified.');
    }

    $parts     = explode(" ", $name);
    $lastname  = array_pop($parts);
    $firstname = implode(" ", $parts);

    return array('firstname' => $firstname, 'lastname' => $lastname);
}

It's worth noting that this assumes the lastname is a single word whereas the firstname can be any combination. For the opposite effect, swap out array_pop() for array_shift().

4
function getFirstName($name) {
    return implode(' ', array_slice(explode(' ', $name), 0, -1));
}

function getLastName($name) {
    return array_slice(explode(' ', $name), -1)[0];
}

$name = 'Johann Sebastian Bach';
$firstName = getFirstName($name);
$lastName = getLastName($name);

echo "first name: $firstName\n";
echo "last name: $lastName\n";

Would result into:

first name: Johann Sebastian  
last name: Bach
3

So my use case was to extract the name of a doctor based on an untrained users input. So I wrote this function to detect the last-comma-first scenario and various titles and suffixes that I may encounter.

Assumptions

  • It will probably require some fine tuning as this has not been beta tested yet. I will try to remember to update this post as I patch the function.
  • The prefix/suffix list will need to be customized for each use case as a comprehensive list would actually be detrimental to functionality. (e.g. A "Mrs. Bishop" or "Dr. Ma" would be empty)
  • Also only middle initial is pulled and the middle names beyond the first encountered are ignored.

Code

function extractName($name)
{
  // Common/expected prefixes.
  $prefix_list = array(
    'mr',
    'mrs',
    'miss',
    'ms',
    'dr',
    'doctor',
  );

  // Common/expected suffixes.
  $suffix_list = array(
    'md',
    'phd',
    'jr',
    'sr',
    'III',
  );

  $parts = explode(' ', $name);

  // Grab the first name in the string.
  do
  {
    $first_name = array_shift($parts);
  } while ($first_name && in_array(str_replace('.', '', strtolower($first_name)), $prefix_list));

  // If the first name ends with a comma it is actually the last name. Adjust.
  if (strpos($first_name, ',') === (strlen($first_name) - 1))
  {
    $last_name = substr($first_name, 0, strlen($first_name) - 1);
    $first_name = array_shift($parts);

    // Only want the middle initial so grab the next text in the array.
    $middle_name = array_shift($parts);

    // If the text is a suffix clear the middle name.
    if (in_array(str_replace('.', '', strtolower($middle_name)), $suffix_list))
    {
      $middle_name = '';
    }
  }
  else
  {
    // Retrieve the last name if not the leading value.
    do
    {
      $last_name = array_pop($parts);
    } while ($last_name && in_array(str_replace('.', '', strtolower($last_name)), $suffix_list));

    // Only want the middle initial so grab the next text in the array.
    $middle_name = array_pop($parts);
  }


  return array($first_name, $last_name, substr($middle_name, 0, 1));
}

Output

enter image description here

3

I have not seen this proposed:

In my case, I needed to split a name into two fields, first and last, regardless of how many names the person had. So I did the following:

$fullName = "Paul Thomas Anderson";
$lastname = end(explode(" ", $fullName));
$firstname = str_replace($lastname,'',$fullName);

This results in $firstname = "Paul Thomas" and $lastname = "Anderson"

The "end()" command just gets the last array element from the exploded name, and then the "str_replace" removes the last name from the full name.

2

This is simple solution if you don`t need middle name:

$name = "John Doe";
$name = trim($username);
$firstName = strtok($name, " "); // John
$lastName = strtok(" "); // Doe

Only one name:

$name = "John";
$name = trim($username);
$firstName = strtok($name, " "); // John
$lastName = strtok(" "); // False

https://www.php.net/manual/en/function.strtok.php

1

I found this served my needs better. It takes the first word as the first name and lumps the rest as the last name.

function splitName($name) {
    $name = trim($name);
    $name = explode(' ', $name);
    $first_name = $name[0];
    unset($name[0]);
    $last_name = implode(' ', $name);
    return array($first_name, $last_name);
}
1

This function works just fine for names in Spanish that includes: first name, middle name, last name, mother's last name and married last name (apply for women only). This format of name is very common in Latin America.

public function split_name(string $name, array $words2join = [], array $remove_prefix = []): object
{
    $result = [];

    $name = strtolower(trim($name));
    $name = preg_replace('/\s+/', ' ', $name);

    $words = explode(' ', $name);

    $name = '';

    foreach($words as $word)
    {
        if (in_array($word, $words2join))
            $word .= '%';
        else
            $word .= ' ';

        $name .= $word;
    }

    $words = explode(' ', trim($name));

    $result['first_name'] = $words[0] ?? '';
    $result['middle_name'] = isset($words[3]) ? (isset($words[2]) ? $words[1] : '') : '';
    $result['last_name'] = isset($words[3]) ? ($words[2] ?? ($words[1] ?? '')) : $words[1] ?? '';
    $result['mother_last_name'] = $words[3] ?? ($words[2] ?? '');
    $result['married_last_name'] = $words[4] ?? '';

    foreach($result as $key => $value)
    {
        $value = ucwords(str_replace('%', ' ', $value));

        if (isset($remove_prefix[$key]))
        {
            $length = strlen($remove_prefix[$key]);

            if (substr($value, 0, $length))
                $value = substr($value, $length + 1, strlen($value));
        }

        $result[$key] = trim($value);
    }


    return (object) $result;
}

Examples:

$result = K7Text::split_name('Edgardo Hormelis Gomez Gaitan', ['del','de','la'], ['married_last_name' => 'de']);
print_r($result);

$result = K7Text::split_name('Miguel H. Pitty De León', ['del','de','la'], ['married_last_name' => 'de']);
print_r($result);

$result = K7Text::split_name('Santiago De La Cruz Abrego Abrego', ['del','de','la'], ['married_last_name' => 'de']);
print_r($result);

$result = K7Text::split_name('María González', ['del','de','la'], ['married_last_name' => 'de']);
print_r($result);

$result = K7Text::split_name('Lucibeth Del Carmen De La Rosa Palacio de Paredes', ['del','de','la'], ['married_last_name' => 'de']);
print_r($result);

Would result into:


stdClass Object
(
    [first_name] => Edgardo
    [middle_name] => Hormelis
    [last_name] => Gomez
    [mother_last_name] => Gaitan
    [married_last_name] => 
)
stdClass Object
(
    [first_name] => Miguel
    [middle_name] => H.
    [last_name] => Pitty
    [mother_last_name] => De León
    [married_last_name] => 
)
stdClass Object
(
    [first_name] => Santiago
    [middle_name] => De La Cruz
    [last_name] => Abrego
    [mother_last_name] => Abrego
    [married_last_name] => 
)
stdClass Object
(
    [first_name] => María
    [middle_name] => 
    [last_name] => González
    [mother_last_name] => 
    [married_last_name] => 
)
stdClass Object
(
    [first_name] => Lucibeth
    [middle_name] => Del Carmen
    [last_name] => De La Rosa
    [mother_last_name] => Palacio
    [married_last_name] => Paredes
)
1
  • 1
    Gracias!. I love the fact that this accounts for Spanish. Dec 30, 2022 at 15:28
0

I use this, it even splits names with and, & and / etc where multiple names are there

function getNames($namestrs){

    $allnames= array();
    $namestrs = trim($namestrs);
    $namestrs = str_replace(array(',',' and ',' & ', '&amp;','/'),'|',$namestrs);

    $namestrs = explode('|',$namestrs);

    foreach($namestrs as $key=> $namestr){
        $namestr = explode(' ',trim($namestr) );

        if(count($namestr)==1 || (count($namestr)==2 && strlen(trim($namestr[1]) )<3)){ 
            $firstname = $namestr[0];
            if(isset( $namestr[1])){
            $middlename = $namestr[1];  
            }
            else{
            $middlename ='';    
            }
            $lastname='';
            $thenames = $namestrs; //print_r($thenames); //echo $key;
            $thenames = array_slice($thenames, $key+1, NULL, TRUE);  //print_r($thenames);

            foreach($thenames as $c=>$a){
                $a = explode(' ',trim($a) );// print_r( $a);

                    if(count($a)>1 && trim($lastname) ==''){
                    $lastname = $a[count($a)-1];

                }                   
            }
        }           
        else if(count($namestr)==2){
            $firstname = $namestr[0];
            $middlename = '';
            $lastname = $namestr[1];
        }
        else if(count($namestr)==3){
            $firstname = $namestr[0];
            $middlename = $namestr[1];
            $lastname = $namestr[2];
        }
        else if(count($namestr)>3){
            $firstname = $namestr[0];
            $middlename = $namestr[1];
            $lastname = str_replace(array( $firstname,$middlename ),"", implode(' ',$namestr));
            $lastname = trim($lastname);
        }

        if($lastname=='3rd')    {
        $lastname = trim($middlename) ." "  .trim($lastname) ;
        $middlename ='';
        }       

        $allnames[] = array('firstname'=>$firstname,'middlename'=>$middlename,'lastname'=>$lastname );
    }

    return $allnames;
}

Sample output Hanna and Mykhoylo Ilyashevych

Array

( [0] => Array ( [firstname] => Hanna [middlename] => [lastname] => Ilyashevych )

[1] => Array
    (
        [firstname] => Mykhoylo
        [middlename] => 
        [lastname] => Ilyashevych
    )

)

0

Here is a very simple way to split full name into first name and last name

$name = "John Smith";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: John

$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Smith

With Middle Name

$name = "Angeler Sherlee Mcgee";
$firstname = strtok($name, ' ');
echo trim($firstname); // Output: Angeler

$lastname = strstr($name, ' ');
echo trim($lastname); // Output: Sherlee Mcgee
0

No need too much work just to get an array with 2 elements:

function parse_name($full_name) {
        $parts = explode(" ", $full_name);

        if (count($parts) > 2) {
            $last = array_pop($parts);
            return [implode(" ", $parts), $last];
        }

        return [$parts[0], $parts[1]];
}

Ex 1 parse_name("Johnny Deep"); outputs :

array(
  0 => "Johnny",
  1 => "Deep"
);

Ex 2 parse_name("Lincoln Johnny Deep"); outputs :

array(
  0 => "Lincoln Johnny",
  1 => "Deep"
);
0

One line code can be like

return (explode(" ", $yourName))[0];
0

Many good simple answers, the array_pop idea was great, however, can get fishy with last names that have a Jr, Sr, I, II, etc.

I came up with this handler to give you first and last name based on the first split. Again, might run into issues regarding some longer or multiple middles names, but this is solely for first and last

$name = 'john public jr';
dump(nameNormalize($name);
function nameNormalize($str)
    {
        $firstname = '';
        $lastname = '';
        $name = [];
        if (stripos($str, ',') === false) {
            $name = explode(' ', $str);
            if (! empty($name[0])) {
                $firstname = $name[0];
                unset($name[0]);
            }
        } else {
            $name = explode(', ', $str);
            if (! empty($name[1])) {
                $firstname = $name[1];
                unset($name[1]);
            }
        }
        $lastname = implode(' ', $name) ?? '';
        if (empty($firstname) && ! empty($lastname)) {
            $firstname = $lastname;
            $lastname = '';
        }

        return [
            'firstname' => $firstname,
            'lastname'  => $lastname,
        ];
    }

Should get back

array:2 [
  "firstname" => "john"
  "lastname" => "public jr"
]

Hope that helps!

-1

This will ignore the middle and just get the first and last.

function split_name($name) {        
    $parts = explode(" ", $name);
    $lastname = array_pop($parts);
    while(count($parts) > 1)
    {
        array_pop($parts);
    }
    $firstname = implode(" ", $parts);

    $name = array(
            'first_name' => $firstname,
            'last_name' => $lastname,
    );

    return $name;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.