我在我的MySQL数据库中有一个描述字段,我在两个不同的页面上访问数据库,一个页面我显示整个字段,但在另一个页面上,我只想显示前50个字符。 如果description字段中的字符串少于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 ...
PHP的方法很简单:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
但是您可以使用以下CSS实现更好的效果:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
现在,假设元素具有固定宽度,浏览器将自动断开并为您添加...
。
您也可以通过以下方式实现所需的修剪:
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 Rights of every human behing”
。
实时代码示例:http://sandbox.onlinephpfunctions.com/code/25484A8B687D1F5AD93F62082B6379662A6B4713
如果字符串长于50个字符,则使用WordWrap()
截断字符串而不中断单词,只需在末尾添加...
即可:
$str = $input;
if( strlen( $input) > 50) {
$str = explode( "\n", wordwrap( $input, 50));
$str = $str[0] . '...';
}
echo $str;
否则,使用substr($input,0,50);
的解决方案将中断单词。