CSS-Tricks*

A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Code Snippets > PHP > Separate First and Last Name Submit one!

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.

Subscribe to The Thread

  1. Orves says:

    $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 says:

    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 says:

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

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---