检查字符串是否超出有限字符然后显示'...'

Sag*_*hal 5 php string conditional function output

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

我有这个echo(substr($sentence,0,29));但是怎么说条件呢?

Sha*_*ran 9

使用mb_strlen()if

$allowedlimit = 29;
if(mb_strlen($sentence)>$allowedlimit)
{
    echo mb_substr($sentence,0,$allowedlimit)."....";
}
Run Code Online (Sandbox Code Playgroud)

或以更简单的方式......(使用三元运算符)

$allowedlimit = 29;
echo (mb_strlen($sentence)>$allowedlimit) ? mb_substr($sentence,0,$allowedlimit)."...." : $sentence;
Run Code Online (Sandbox Code Playgroud)

在一个功能:

function app_shortString($string, $limit = 32) {
     return (mb_strlen($string)>$limit) ? mb_substr($string,0,$limit)." ..." : $string;
}
Run Code Online (Sandbox Code Playgroud)