Get first n characters of a string

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

    I developed a function for this use

     function str_short($string,$limit)
            {
                $len=strlen($string);
                if($len>$limit)
                {
                 $to_sub=$len-$limit;
                 $crop_temp=substr($string,0,-$to_sub);
                 return $crop_len=$crop_temp."...";
                }
                else
                {
                    return $string;
                }
            }
    

    you just call the function with string and limite
    eg:str_short("hahahahahah",5);
    it will cut of your string and add "..." at the end
    :)

提交回复
热议问题