Limit String Length

后端 未结 10 1247
不思量自难忘°
不思量自难忘° 2020-12-01 03:56

I\'m looking for a way to limit a string in php and add on ... at the end if the string was too long.

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 04:40

    You can use the wordwrap() function then explode on newline and take the first part, if you don't want to split words.

    $str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
    $str = wordwrap($str, 28);
    $str = explode("\n", $str);
    $str = $str[0] . '...';
    

    Source: https://stackoverflow.com/a/1104329/1060423

    If you don't care about splitting words, then simply use the php substr function.

    echo substr($str, 0, 28) . '...';
    

提交回复
热议问题