减少PHP字符串的长度并插入省略号 [英] Cutting down a length of a PHP string and inserting an ellipses

查看:29
本文介绍了减少PHP字符串的长度并插入省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把像 reallyreallyreallyreallyreallylongfilename 这样的长字符串变成类似 reallyreallyre...yreallyreally 的东西.

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

基本上,找到字符串的中间位置并替换那里的所有内容,直到字符串的长度为 <包括省略号在内的 30 个字符,表示字符串的某些部分已被替换.

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.

这是我尝试过的代码:

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 是.

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.

希望你能理解我的问题,我认为我没有很好地解释它 8)

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

谢谢.

推荐答案

怎么样:

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

这篇关于减少PHP字符串的长度并插入省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆