Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Separate First and Last Name

$name = "John S Smith";

list($fname, $lname) = split(' ', $name,2);

echo "First Name: $fname, Last Name: $lname";

Works with or without middle name.

Comments

  1. Orves
    Permalink to comment#
    $name = "John S. Doe";
    list($fname, $lname) = explode(' ', $name,2);
    echo "First Name: $fname, Last Name: $lname";

    split() function is deprecated in PHP > 5.3

  2. Mike
    Permalink to comment#

    Or maybe something more like this to literally get their first and last name, no matter how much junk they enter

    $name = "James Samuel Murphy 'I took that waaaaay too far' Adams";
    list( $fname, $mname, $lname ) = explode( ' ', $name, 3 );		
    if ( is_null($lname) ) //Meaning only two names were entered...
    {
        $lastname = $mname;
    }
    else
    {
        $lname = explode( ' ', $lname );
        $size = sizeof($lname);
        $lastname = $lname[$size-1];
    }
    echo "First Name: $fname, Last Name: $lastname";
  3. Emmanuel
    Permalink to comment#

    Perhaps a better way to go would be to strip multiple whitespace from the name before exploding it.
    Like this:

    list($fname,$lname) = explode(‘ ‘, str_replace(‘/\s+/gi’,’ ‘,$name), 2);

  4. Bretticus

    Note that with the limit in place, $lname always ends up with the middle names and/or initials. Also, to make this accurate with the limit param in place, you need to ensure that there are no extra spaces. preg_split with a look ahead assertion can solve these two issues with one line of code still:

    list($fname,$lname) = preg_split('/\s+(?=[^\s]+$)/', $name, 2); 
  5. Immanuelprabhu
    Permalink to comment#

    Hi, help me to split my name IMMANUELPRABHU JOSHUA into First name, Middle name & Surname

    Regards
    Immanuel.J

  6. ubaid
    Permalink to comment#

    Now time is for using explode() function :).

  7. Preet
    Permalink to comment#

    Easy just do this:

    
    $msgString = "Manpreet Singh Marwaha";
    
    $result = explode(" ",$msgString);
    
    echo $result[0]; //Manpreet
    echo $result[1]; //Singh
    echo $result[2]; //Marwaha
    
    

    easy!!!

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```