Split the first letter from variable

前端 未结 4 1097
挽巷
挽巷 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.
    0 讨论(0)
  • 2021-01-23 10:25

    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];
    
    0 讨论(0)
  • 2021-01-23 10:31
    $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) */)
    
    0 讨论(0)
  • 2021-01-23 10:35

    You can get the first letter of a string using array syntax!

    $firstletter = $userData['name'][0];
    
    0 讨论(0)
提交回复
热议问题