Splitting a name field into firstname/surname

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
studley
Forum Newbie
Posts: 5
Joined: Fri Dec 31, 2004 5:10 am

Splitting a name field into firstname/surname

Post 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?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
studley
Forum Newbie
Posts: 5
Joined: Fri Dec 31, 2004 5:10 am

Post 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.
Post Reply