您也可以通过以下方式实现所需的修剪:
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