加。。。如果字符串太长 PHP

2022-08-30 06:41:58

我的MySQL数据库中有一个描述字段,我在两个不同的页面上访问数据库,一个页面显示整个字段,但另一个页面,我只想显示前50个字符。如果描述字段中的字符串少于50个字符,那么它不会显示... ,但如果不是,我将显示...在前 50 个字符之后。

示例(完整字符串):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

示例 2(前 50 个字符):

Hello, this is the first example, where I am going ...

答案 1

PHP的做到这一点的方法很简单:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

但是你可以用这个CSS实现更好的效果:

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

现在,假设元素具有固定的宽度,浏览器将自动中断并为您添加。...


答案 2

您也可以通过以下方式实现所需的修剪:

mb_strimwidth("Hello World", 0, 10, "...");

哪里:

  • Hello World:要修剪的字符串。
  • 0:字符串开头的字符数。
  • 10:修剪后的字符串的长度。
  • ...:在修剪后的字符串末尾添加的字符串。

这将返回 。Hello W...

请注意,10 是截断字符串的长度 + 添加的字符串!

文档:http://php.net/manual/en/function.mb-strimwidth.php

要避免截断单词:

在呈现文本摘录的情况下,可能应避免截断单词。如果对截断文本的长度没有硬性要求,除了这里提到的,还可以使用以下内容来截断并防止剪切最后一个单词。wordwrap()

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

在本例中,将为 。$preview"Knowledge is a natural right of every human being"

实时代码示例:http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713


推荐