简体   繁体   English

PHP:使用“ ..”正确截断字符串

[英]PHP: properly truncating strings with “..”

Currently, the method I use to truncate strings is: echo substr($message, 0, 30).".."; 当前,我用于截断字符串的方法是: echo substr($message, 0, 30)."..";

How do I show the dots only in the case that the string has been truncated? 仅在字符串被截断的情况下,如何显示点?

Just check the length to see if it's more than 30 characters or not: 只需检查其长度,看看它是否超过30个字符:

if (strlen($message) > 30)
{
    echo substr($message, 0, 30)."..";
}
else
{
    echo $message;
}

The typographic nitpick in me has this to add: the correct character to use is the ellipsis which comprises this character , three dots ... , or its HTML entity … 我中的印刷版nitpick要添加以下内容:正确使用的字符是由以下字符组成的省略号: 三个...或其HTML实体… .

Just check the length of the original string to see if it needs to be truncated. 只需检查原始字符串的长度以查看是否需要将其截断即可。 If it is longer than 30, truncate the string and add the dots on the end: 如果长度大于30,则截断字符串并在末尾添加点:

if (strlen($message) > 30) {
 echo substr($message, 0, 30)."..";
} else {
 echo $message;
}
if (strlen($message) > 30) {
  echo substr($message, 0, 30) . "..";
} else {
  echo $message;
}

It should be noted that the strlen() function does not count characters, it counts bytes. 应当注意,strlen()函数不计算字符,而是计算字节。 If you are using UTF-8 encoding you may end up with 1 character that is counted as up to 4 bytes. 如果使用的是UTF-8编码,则可能会以1个字符结尾,该字符最多可算作4个字节。 The proper way to do this would be something like: 正确的方法是:

echo mb_strlen($message) > 30 ? mb_substr($message, 0, 30) . "..." : $message;

You could do: 您可以这样做:

echo strlen($message) > 30 ? substr($message, 0, 30) . '..' : $mssage;

Basically, it's like (but shorter): 基本上,它就像(但更短):

if (strlen($message) > 30) {
    echo substr($message, 0, 30) . "..";
} else {
    echo $message;
}

添加strlen()条件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM