Welcome to WebmasterWorld Guest from 54.167.46.29

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Display last word from a variable

     
1:53 pm on Nov 30, 2009 (gmt 0)

Junior Member

5+ Year Member

joined:July 17, 2006
posts:137
votes: 0


i have a variable called $full_names

if i echo this variable, i get a full name of a person in our database. Some full names have middle names so therefore having 3 total words and some have first name and last name which gives me 2 words and in rare occassions some have 4 words.

Can anyone tell me how I can get the last word and the first letter in this variable? so that i can echo The initial for the first name and the last name. So for example the following full name: James Carpenter Robertson, needs to output: J. Robertson

any suggestions would be appreciated. thanks

2:24 pm on Nov 30, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:May 6, 2008
posts:2011
votes: 0


First letter is easy.

echo $full_names[0];

Next question is tricky. Best solution I can think of is to work backwards with a loop reading in the last name characters till you hit a space. Get the character count..

$count = strlen($full_names);

Then use this variable in a while loop counting backwards and storing the characters in a variable(backwards) until you hit a space. Once you hit the space you'll have your last name.

2:46 pm on Nov 30, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member dreamcatcher is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Mar 30, 2003
posts:3719
votes: 0


Easiest way for last name is to use explode [php.net]

$string = 'James Carpenter Robertson';
$name = explode(' ',$string);
echo $name[count($name)-1)];

You can also use strrpos [php.net] to get the last occurence of a space. Combine this with substr [php.net] and strlen [php.net]:

$string = 'James Carpenter Robertson';
echo substr($string,strrpos($string, ' '),strlen($string));

dc

2:56 pm on Nov 30, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:May 6, 2008
posts:2011
votes: 0


That works too, a lot cleaner and easier.
3:05 pm on Nov 30, 2009 (gmt 0)

Junior Member

5+ Year Member

joined:July 17, 2006
posts:137
votes: 0


strrpos method works perfectly. many thanks for your help dreamcatcher and StoutFiles
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members