如果字符串超过一定数量的字符,如何用MySQL回显部分UTF-8 varchar字符串?

时间:2023-01-06 11:06:32

I'm currently using the substr() function which works fine for characters written in english. But when I apply that to characters written in greek, the text is cut with a strange character (a questionmark inside a diamond shape) appearing before the 3 fullstops (...). Below is the code, thanks:

我目前正在使用substr()函数,该函数适用于用英语编写的字符。但是当我将它应用于用希腊语写的字符时,文本会被切割成一个奇怪的字符(钻石形状内的问号)出现在3个完整停止之前(...)。以下是代码,谢谢:

$string //a varchar string written in greek and called from the database 
if (strlen($string) > 200) {
    echo substr($string, 0, 200).'...';
}

1 个解决方案

#1


1  

Use multibyte functions like so:

使用多字节函数,如下所示:

mb_internal_encoding( "UTF-8" );

if( mb_strlen( $string ) > 200 ) {
   echo mb_substr( $string, 0, 200 ) . "...";
}

The normal functions work on bytes and don't have any character awareness like you are expecting from them. Text using common english characters in UTF-8 are all 1 byte per character, so the normal functions accidentally work for them.

普通函数对字节起作用,并且没有像你期望的那样具有任何字符感知。使用UTF-8中常见英文字符的文本每个字符都是1个字节,因此正常功能会意外地为它们工作。

#1


1  

Use multibyte functions like so:

使用多字节函数,如下所示:

mb_internal_encoding( "UTF-8" );

if( mb_strlen( $string ) > 200 ) {
   echo mb_substr( $string, 0, 200 ) . "...";
}

The normal functions work on bytes and don't have any character awareness like you are expecting from them. Text using common english characters in UTF-8 are all 1 byte per character, so the normal functions accidentally work for them.

普通函数对字节起作用,并且没有像你期望的那样具有任何字符感知。使用UTF-8中常见英文字符的文本每个字符都是1个字节,因此正常功能会意外地为它们工作。