gpt4 book ai didi

php - 检查字符串是否超过限制字符然后显示 '...'

转载 作者:可可西里 更新时间:2023-11-01 13:40:03 25 4
gpt4 key购买 nike

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

我有这个 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;
}

关于php - 检查字符串是否超过限制字符然后显示 '...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com