Get first n characters of a string

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

    If you want to cut being careful to don't split words you can do the following

    function ellipse($str,$n_chars,$crop_str=' [...]')
    {
        $buff=strip_tags($str);
        if(strlen($buff) > $n_chars)
        {
            $cut_index=strpos($buff,' ',$n_chars);
            $buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
        }
        return $buff;
    }
    

    if $str is shorter than $n_chars returns it untouched.

    If $str is equal to $n_chars returns it as is as well.

    if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.

    NOTE: be aware that this method will remove all tags in case of HTML.

提交回复
热议问题