Cutting down a length of a PHP string and inserting an ellipses

China☆狼群 提交于 2019-12-10 13:57:35

问题


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.


回答1:


How about:

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


来源:https://stackoverflow.com/questions/3076513/cutting-down-a-length-of-a-php-string-and-inserting-an-ellipses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!