How to get first x chars from a string, without cutting off the last word?

后端 未结 13 1351
再見小時候
再見小時候 2020-11-28 10:24

I have the following string in a variable.

Stack Overflow is as frictionless and painless to use as we could make it.

I want to fetch first 28 characte

13条回答
  •  星月不相逢
    2020-11-28 10:42

    function truncate( $string, $limit, $break=" ", $pad="...") {
    
     // return with no change if string is shorter than $limit
     if(strlen($string) <= $limit){
        return $string;
     }
    
     $string = substr($string, 0, $limit);
     if(false !== ($breakpoint = strrpos($string, $break))){
        $string = substr($string, 0, $breakpoint);
     }
     return $string . $pad;
    }
    

提交回复
热议问题