Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first character of UTF-8 string

Tags:

php

yii

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?

like image 494
Nick_NY Avatar asked Nov 22 '12 08:11

Nick_NY


People also ask

How do you get the first character of a string?

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 .

How do you get the first character of a string in typescript?

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.

What is mb_ substr?

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.

How do you get first character of a string in react native?

You should use the charAt() method at index 0 for selecting the first character of the string.


2 Answers

$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" />
like image 99
Botond Balázs Avatar answered Sep 19 '22 05:09

Botond Balázs


There are several things you need to consider:

  1. Check that data in the DB is being stored as UTF-8
  2. Check that the client connection to the DB is in UTF-8 (for example, in mysql see: http://www.php.net/manual/en/mysqli.character-set-name.php)
  3. Make sure that the page has it's content-type set as UTF-8 [you can use header('Content-Type: utf-8'); ]
  4. Try setting the internal encoding, using mb_internal_encoding("UTF-8");
  5. Use mb_substr instead of array index notation
like image 33
Paul S Avatar answered Sep 20 '22 05:09

Paul S