php truncate string if longer than limit and put some omission at the end..similar to ruby

試著忘記壹切 提交于 2019-11-29 08:21:10
function substr_with_ellipsis($string, $chars = 100)
{
    preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
    $new_string = $matches[0];
    return ($new_string === $string) ? $string : $new_string . '…';
}
function truncate($string,$length=100,$appendStr="..."){
    $truncated_str = "";
    $useAppendStr = (strlen($string) > intval($length))? true:false;
    $truncated_str = substr($string,0,$length);
    $truncated_str .= ($useAppendStr)? $appendStr:"";
    return $truncated_str;
}

You could even edit the function so that you could either chose to cut at the exact maximum length or to respect word boundaries...
The choice is basically yours

class StringHelper
{

    public static function truncate($string, $length = 100, $append = "...")
    {
        if (strlen($string) <= intval($length)) {
            return $string;
        }

        return substr($string, 0, $length) . $append;
    }

}

Static universal method for truncate that I use with Yii framework.

Bing

Built on @OkekeEmmanuelOluchu's answer. Little bit short and cleaner:

function truncateString($string, $length = 100, $append = "..."){
    $truncated_str = substr($string, 0, $length);
    $truncated_str .= strlen($string) > intval($length) ? $append : "";
    return $truncated_str;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!