Forum Moderators: coopster
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
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.
$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