views:

73

answers:

3

Variable $name (string) gives something like (possible values):

"Elton John"
"2012"
" George Bush"
" Julia"
"Marry III Great"

Want to catch the first letter of $name and add it to $letter variable.

It's important how many words (divided with spaces " ") the string has:

  1. If there is just one word, set $letter to the first letter of the first word.

  2. If there is more than one word, set $letter to the first letter of the second word.

  3. If $name is empty, set $letter to 'undefined'.

Thanks.

+3  A: 

You could just do an explode or a preg_split and count the pieces:

$parts = preg_split('/\s/', $subject, -1, PREG_SPLIT_NO_EMPTY);
if (count($parts) == 1)
   ...

An alternative with explode:

$subject = trim(subject);
$parts = explode(' ', $subject);

This works too if you are certain there are only spaces.

Blizz
thanks, but it won't work if there is a whitespace before first word (it can be so, users choice).
Happy
@Ignatz Both work fine; `PREG_SPLIT_NO_EMPTY` stops `preg_split` from returning empty blocks in the first code snippet, and `trim` removes the whitespace from the ends in the second
Michael Mrozek
+3  A: 
$names = explode(' ', trim($name));
if (empty($names))
    $letters = 'undefined';
else if(count($names)==1)
    $letters = substr($names[0],0,1);
else 
    $letters = substr($names[1],0,1);
a.aman
You could also return `$names[1][0]` instead of using `substr()`.
alex
thanks for the tip..
a.aman
+1  A: 

Or you could just use $letter = $name{0};

Charles Harris