Hau Le
Hau Le

Reputation: 677

How to cut a part of string with japan character in PHP?

I have a string as: $fullname = 'ワタナベサン';

And some line code for cut a part of string with condition:

if (strlen ( $fullname ) >= 14)
    $this->FullName = substr ( $fullname, 0, 10 ) . '...';
else
    $this->FullName = $fullname;

But the result appears as wrong string as: 'ワタナ�...'.

Upvotes: 0

Views: 1616

Answers (2)

deceze
deceze

Reputation: 522042

substr, and all other core PHP string functions, are not multibyte aware and cannot treat multibyte strings correctly. They only work correctly on ASCII strings or other single-byte encodings. To manipulate multibyte strings correctly, in most cases you need to use the equivalent functions in the MB extension.

See What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text for more information. Welcome to the rabbit hole of character encodings; you have a lot to learn. :o)

Upvotes: 2

codeaken
codeaken

Reputation: 884

You will need to use the multi-byte versions of the string functions when working with Japanese characters. Use mb_substr instead of substr and mb_strlen instead of strlen.

Upvotes: 3

Related Questions