Split the first letter from variable

蹲街弑〆低调 提交于 2019-12-02 05:41:10
$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) */)
hakre

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 integer 1 and false to 0.
  • Reducing the number of ifs 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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!