我想列出列表中的一些项目,但最多可以列出几个字符,如果字符限制达到,则只显示...
。
我有这个echo(substr($sentence,0,29));
,但是它的条件是什么?
答案 0 :(得分:9)
使用mb_strlen()
和if
$allowedlimit = 29;
if(mb_strlen($sentence)>$allowedlimit)
{
echo mb_substr($sentence,0,$allowedlimit)."....";
}
或以更简单的方式......(使用三元运算符)
$allowedlimit = 29;
echo (mb_strlen($sentence)>$allowedlimit) ? mb_substr($sentence,0,$allowedlimit)."...." : $sentence;
在一个函数中:
function app_shortString($string, $limit = 32) {
return (mb_strlen($string)>$limit) ? mb_substr($string,0,$limit)." ..." : $string;
}
答案 1 :(得分:3)
这应该这样做:
if(strlen($sentence) >= 30) {
echo substr($sentence,0,29)."...";
} else {
echo $sentence;
}
关于strlen()
的更多信息:http://www.php.net/manual/de/function.strlen.php
编辑/废话,错误的功能,sry。 ._。
答案 2 :(得分:1)
$text = 'this is a long string that is over 28 characters long';
strlen($text) > 28 ? substr($text, 0, 28) .'...' : $text;
gives: this is a long string that i...
$text = 'this is a short string!';
echo strlen($text) > 28 ? substr($text, 0, 28) .'...' : $text;
gives: this is a short string!