Page 1 of 1

Splitting a name field into firstname/surname

Posted: Sun Jan 22, 2006 3:58 am
by studley
Hi there,

I have a single "name" input field, and when submitted I want to look for the first space in the name, put anything before it into a "firstname" field, and anything after it into "surname".

At the moment I'm doing it like this (because its the only way I know how):

Code: Select all

<?
$fullnameexplode = explode(' ', $fullname); 
$firstname=$fullnameexplode[0];
$surname=$fullnameexplode[1];
?>
However, if there's more than one space in the name - e.g. Billy Bob Thornton, it's ending up with Billy in the $firstname, Bob in the $surname, and Thornton is getting dropped. How do I get my $surname to pick up everything except the $firstname?

Posted: Sun Jan 22, 2006 7:44 am
by Chris Corbyn

Code: Select all

$parts = preg_split('/\s+/', $string);
Don't forget that in some countries people will put there surname first (Romania being one I dealt with recently) and many names have several parts to them. This is going to cause you a lot of problems. I'd use clearly defined form fields.

Posted: Sun Jan 22, 2006 7:49 am
by studley
Thanks very much - the field is within an admin system which only one user is accessing, so all names will be in the same format, this is good enough for him.