I get an UTF-8 string from db, and trying to echo its first character:
$title = $model->title;
echo $title[0];
I get: �
What's wrong?
The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
1. Get the First Letter of the String. You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str.
In PHP, mb_substr() is used to return the selected part of a given string. The multibyte safe substr() works based on the number of characters. It counts the position from the starting of the string. It will return 0 for the first character position and 1 for the second position character, and so on.
You should use the charAt() method at index 0 for selecting the first character of the string.
$first_char = mb_substr($title, 0, 1);
You need to use PHP's multibyte string functions to properly handle Unicode strings:
http://www.php.net/manual/en/ref.mbstring.php
http://www.php.net/manual/en/function.mb-substr.php
You'll also need to specify the character encoding in the <head>
of your HTML:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
or:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
There are several things you need to consider:
header('Content-Type: utf-8');
]mb_internal_encoding("UTF-8");
mb_substr
instead of array index notationIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With