How to Truncate a word which is having unicode characters without breaking the unicode?

StackOverflow https://stackoverflow.com/questions/16729814

  •  30-05-2022
  •  | 
  •  

質問

I am having a word like "Stefan Äöüéèêë". I want to truncate this string after 20 characters...but it is giving me like Stefan Äöüéèê� . I am using following code for this.

$string = "Stefan Äöüéèêë";
if(strlen($string) > 20){
       $string = substr($string, 0, 20) . '...';      
}

How can I get string which is safely truncated.

役に立ちましたか?

解決

Use the multibyte version of it: http://php.net/manual/de/function.mb-substr.php

Further more here is a list of unicode unsafe methods that is quite handy: http://www.phpwact.org/php/i18n/utf-8

Note: strlen does return the wrong value

他のヒント

try this friend , if you decode the string then it will give proper length of string.

$string = "Stefan Äöüéèêë";
$string= utf8_decode($string);
echo strlen($string);
if(strlen($string) > 10){
    $string = mb_substr($string, 0, 10);   
}
echo $string;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top