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:
If there is just one word, set
$letter
to the first letter of t开发者_开发百科he first word.If there is more than one word, set
$letter
to the first letter of the second word.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};
精彩评论