检查字符串是否超过限制字符,然后显示'';


check if string exceeds limited characters then show '...'

我想列出列表中的一些项目,但最多只能列出几个字符,如果达到字符限制,则只显示...

我有这个echo(substr($sentence,0,29));,但它的条件是什么?

使用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;
}

这应该做到:

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

关于strlen()的更多信息:http://www.php.net/manual/de/function.strlen.php

编辑/崩溃,脑子里有错误的功能,sry._。

$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!