开发者

PHP get the letter

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 t开发者_开发百科he 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.


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


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.


Or you could just use

$letter = $name{0};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜