homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Display last word from a variable

 1:53 pm on Nov 30, 2009 (gmt 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)

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)

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));



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

That works too, a lot cleaner and easier.


 3:05 pm on Nov 30, 2009 (gmt 0)

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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved