Split the first letter from variable

前端 未结 4 1100
挽巷
挽巷 2021-01-23 10:17

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?

4条回答
  •  被撕碎了的回忆
    2021-01-23 10:19

    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.

提交回复
热议问题