Welcome to WebmasterWorld Guest from 54.167.177.207

Forum Moderators: coopster & jatar k

Display last word from a variable

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

5+ Year Member



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)

WebmasterWorld Senior Member 5+ Year Member



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)

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



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)

WebmasterWorld Senior Member 5+ Year Member



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

5+ Year Member



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

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month