Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first character of string contain special characters using php?

I used string[0] to shorten and show first character of user names/ lastnames. And it worked great until the user's name is starting with a special character like ö, ä, ü.

for example:

$name = 'über';
echo $name[0];
// echoes nothing

Meanwhile I am using mb_substr($string, 0, 1) instead. But i really miss $name[0] :). It was much faster and shorter. I still wonder what the reason is and if there is a way to use this syntax with special chars.

like image 515
Skeletor Avatar asked Dec 11 '25 05:12

Skeletor


1 Answers

The character ü is not a single byte character. It is a multi-byte (two byte) character.

char

You are trying to access the first byte of the character string, so it doesn't work. Just for this very reason, mb_substr has been designed.

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

If you are just trying to do the $name[0], it get's the first character of the multi-byte character, which is just an empty string or a control character to display the .. above the u. (take it just for example, like .. + u = ü).

like image 117
Praveen Kumar Purushothaman Avatar answered Dec 13 '25 18:12

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!