Alex Rivera | Logout

Truncate a string to first n characters of a string and add three dots if any characters are removed

Asked 2010-07-01T21:28:19.950
393

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?

Edit
Report

3 Answers

7
if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";
answered 2010-07-01T21:31:02.160
1

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
:)

answered 2013-02-04T06:08:03.240
1

This is what i do

    function cutat($num, $tt){
        if (mb_strlen($tt)>$num){
            $tt=mb_substr($tt,0,$num-2).'...';
        }
        return $tt;
    }

where $num stands for number of chars, and $tt the string for manipulation.

answered 2013-03-21T16:56:42.717

Your Answer