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

时间:2014-04-25 11:33:09

标签: php string function conditional output

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

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

3 个答案:

答案 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!