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

后端 未结 13 1345
再見小時候
再見小時候 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:51

    Here's one way you could do it:

    $str = "Stack Overflow is as frictionless and painless to use as we could make it.";
    
    $strMax = 28;
    $strTrim = ((strlen($str) < $strMax-3) ? $str : substr($str, 0, $strMax-3)."...");
    
    //or this way to trim to full words
    $strFull = ((strlen($str) < $strMax-3) ? $str : strrpos(substr($str, 0, $strMax-3),' ')."...");
    

提交回复
热议问题