I need to split the first letter from variable $name. How I can to do it?
$name = $userData['name'];
How I can to get the first letter?
and please check if it correct:
if($userData['gender'] == 'male'){
if($firstletter=='i'){
$picture = ImageCreateFromPNG ($global['maleBackgroundImages'][1]);
}else{
$picture = ImageCreateFromPNG ($global['maleBackgroundImages'][2]);}
}else{
if($firstletter=='i'){
$picture = ImageCreateFromPNG ($global['maleBackgroundImages'][1]);
}else{
$picture = ImageCreateFromPNG ($global['maleBackgroundImages'][2]);}
}
$userData['name'][0]
Offsets in strings can be accessed like arrays. Be aware that this assumes your strings are in a single byte encoding. If you have multi-byte encoded strings, you need:
mb_substr($userData['name'], 0, 1, 'UTF-8' /* (the correct encoding) */)
Moved over from the duplicate question. Code slightly differs but covers the same.
First of all you not only need to know in which language the string is (hebrew) but also which character encoding is used.
Let's say the input is inside a variable called $letters
and the encoding is UTF-8. The letter you want to compare against is א
('HEBREW LETTER ALEF' (U+05D0)).
The first cliff to ship around is to have the UTF-8 representation safely inside your PHP script which might be in some other than UTF-8 encoding:
$compareLetter = "\xD7\x90"; // UTF-8 'HEBREW LETTER ALEF' (U+05D0)
The next cliff is to extract the first letter from the input. As we know by the definition of $compareLetter
the byte-size is two. So we need to compare the first two bytes:
$isSame = substr($letters, 0, 2) === $compareLetter;
The rest of your code then could stay the same (but could also be streamlined as I do now):
$png = $global['maleBackgroundImages'][4 + $isSame];
$picture = ImageCreateFromPNG($png);
The full code example:
...
$compareLetter = "\xD7\x90"; // UTF-8 'HEBREW LETTER ALEF' (U+05D0)
$isSame = substr($letters, 0, 2) === $compareLetter;
$png = $global['maleBackgroundImages'][4 + $isSame];
$picture = ImageCreateFromPNG($png);
Character Encoding Notes:
- Know which character encoding is used: Everwhere, including places like
- Input strings
- The PHP script file
- Output
- Treat the string-data in respect to its encoding.
Some additional notes:
- Initializes variables before use.
- If you have got a simple decision, you often can express it as a calculation. Boolean
true
equals to integer1
andfalse
to0
. - Reducing the number of
if
s often reduces the code. That helps you to do less errors.
You can get the first letter of a string using array syntax!
$firstletter = $userData['name'][0];
This is just a supplementary answer.
If you want neat single character access with an utf-8 string, you can do to do this:
$chars = preg_split( '/(?<!^)(?!$)/u', $userData['name'] );
echo $chars[0];
来源:https://stackoverflow.com/questions/13858706/split-the-first-letter-from-variable