I was recently looking for a way to clean up the sign up form for a project I’m working on. I realised I could merge the First name and Last name fields on the form but I needed a way to split the name up afterwards. So after a quick “Google” I came up with a way. The code below splits the name at the first space.
Input: John S Smith
Output: First Name: John Last Name: S Smith
// PHP
$name = "John S Smith";
list($fname, $lname) = split(' ', $name,2);
echo "First Name: $fname, Last Name: $lname";

Comments
very useful and very nice article thank you
It’s somehow of what I thought that I would do. But this kind of solution doesn’t work for some arabic complex names (that consists of more than one part).
also, is it possible to have it split 4 names in the $name field, so if i input Mr John Smith Jr the first name will be Mr John and last name would be Mith Jr? would i have to do a preg_match or something?
great stuff:)
i’m a php_newb… how can do the opposite with the first and last name so the middle initial/name goes with the first name rather than the last?
Hey,
It’s a great tutorial for split description with php but what happen if string having html tags in it.
Here is a tutorial to work with that condition
http://phpschools.freehostia.com/other-stuff/split-html-description-in-php
$name = “Kent Mathisen”;
list($first, $last) = explode(” “, $name);
echo “First name: ” . $first . “, last name: ” . $last;
Won’t give any errors or warnings
from http://php.net/split :
Note: As of PHP 5.3.0 the regex extension is deprecated, calling this function will issue an E_DEPRECATED notice.