缩短 PHP 字符串的长度并插入省略号

发布于 2024-09-05 23:30:05 字数 636 浏览 2 评论 0原文

我想将像 reallyreallyreallyreallylongfilename 这样的长字符串变成 reallyreallyre...yreallyreally 这样的东西。

基本上,找到字符串的中间并替换其中的所有内容,直到字符串的长度 < 30 个字符,包括一个省略号,表示字符串的某些部分已被替换。

这是我尝试过的代码:

function cutString($input, $maxLen = 30)
{
    if(strlen($input) < $maxLen)
    {
        return $input;
    }

    $midPoint = floor(strlen($input) / 2);
    $startPoint = $midPoint - 1;

    return substr_replace($input, '...', $startPoint, 3);
}

它找到字符串的中心并用 . 替换两侧的字符,但问题是我不知道如何将其削减为30 个字符,或任何 $maxLen

希望您能理解我的问题,我认为我在解释方面做得不太好 8)

谢谢。

I want to turn a long string like reallyreallyreallyreallyreallylongfilename into something like reallyreallyre...yreallyreally.

Basically, find the middle of the string and replace everything there until the length of the string is < 30 characters including an ellipses to signify there has been parts of the string replaced.

This is my code where I have tried this:

function cutString($input, $maxLen = 30)
{
    if(strlen($input) < $maxLen)
    {
        return $input;
    }

    $midPoint = floor(strlen($input) / 2);
    $startPoint = $midPoint - 1;

    return substr_replace($input, '...', $startPoint, 3);
}

It finds the center of the string and replaces a character either side with . but the thing is I can't work out how to make it cut it down to 30 characters, or whatever $maxLen is.

Hopefully you understand my question, I don't think I did a very good job at explaining it 8)

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摇划花蜜的午后 2024-09-12 23:30:06

怎么样:

if (strlen($input) > $maxLen) {
    $characters = floor($maxLen / 2);
    return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}

How about:

if (strlen($input) > $maxLen) {
    $characters = floor($maxLen / 2);
    return substr($input, 0, $characters) . '...' . substr($input, -1 * $characters);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文