Get first n characters of a string

前端 未结 19 1378
萌比男神i
萌比男神i 2020-11-22 13:06

How can I get the first n characters of a string in PHP? What\'s the fastest way to trim a string to a specific number of characters, and append \'...\' if needed?

19条回答
  •  温柔的废话
    2020-11-22 13:39

    The function I used:

    function cutAfter($string, $len = 30, $append = '...') {
            return (strlen($string) > $len) ? 
              substr($string, 0, $len - strlen($append)) . $append : 
              $string;
    }
    

    See it in action.

提交回复
热议问题