Get first n characters of a string

前端 未结 19 1131
萌比男神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:19

    To create within a function (for repeat usage) and dynamical limited length, use:

    function string_length_cutoff($string, $limit, $subtext = '...')
    {
        return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
    }
    
    // example usage:
    echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
    
    // or (for custom substitution text
    echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
    

提交回复
热议问题