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

475,851

Solution 1

//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';

Update:

Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):

$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;

So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'

Update 2:

Or as function:

function truncate($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

Update 3:

It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:

function truncate($string,$length=100,$append="…") {
  $string = trim($string);

  if(strlen($string) > $length) {
    $string = wordwrap($string, $length);
    $string = explode("\n", $string, 2);
    $string = $string[0] . $append;
  }

  return $string;
}

Solution 2

This functionality has been built into PHP since version 4.0.6. See the docs.

echo mb_strimwidth('Hello World', 0, 10, '...');

// outputs Hello W...

Note that the trimmarker (the ellipsis above) are included in the truncated length.

Solution 3

The Multibyte extension can come in handy if you need control over the string charset.

$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
  $string = mb_substr($string, 0, $length - 3, $charset) . '...';
}

Solution 4

sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.

eg: we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.

phew, am bad at explaining, here is the code.

class Fun {

    public function limit_text($text, $len) {
        if (strlen($text) < $len) {
            return $text;
        }
        $text_words = explode(' ', $text);
        $out = null;


        foreach ($text_words as $word) {
            if ((strlen($word) > $len) && $out == null) {

                return substr($word, 0, $len) . "...";
            }
            if ((strlen($out) + strlen($word)) > $len) {
                return $out . "...";
            }
            $out.=" " . $word;
        }
        return $out;
    }

}

Solution 5

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.

Share:
475,851
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on August 09, 2021

Comments

  • Alex
    Alex almost 3 years

    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?

  • Robert
    Robert almost 14 years
    Could explain why this approach is best instead of just asserting that it is?
  • TravisO
    TravisO almost 14 years
    @Robert it's simple, and abstracting means you don't have to retype the code over and over. And most importantly, if you do find a better way to do this, or want something more complex, you only change this 1 function instead of 50 pieces of code.
  • TravisO
    TravisO almost 14 years
    This code will always add ... to the string, which he didn't want.
  • fello
    fello about 13 years
    This code is adding the three dots to the string? my code it has a link tag <a> and when I link it it will link it together with the three dots which it will come as a different value.
  • Keith
    Keith about 11 years
    might be best to replace with ellipsis ( … ) rather than 3 dots ( ... )
  • Kenton de Jong
    Kenton de Jong almost 11 years
    I love this, but I changed it and use the following to remove whitespace at the end: $string = substr(trim($string),0,10).'...'; That way you get something like "I like to..." instead of "I like to ...".
  • Phil Perry
    Phil Perry over 10 years
    Fix: substr of $var, not $string. Test against $limit + 3 so that you don't trim a string just over the limit. Depending on your application (e.g., HTML output), consider using an entity &hellip; instead (typographically more pleasing). As suggested earlier, trim off any non-letters from the end of the (shortened) string before appending the ellipsis. Finally, watch out if you're in a multibyte (e.g., UTF-8) environment -- you can't use strlen() and substr().
  • pdwalker
    pdwalker over 9 years
    Dan, you might want to be a bit more specific about which part of the top answer did not work for you. The function truncate() worked perfectly for me and the advantage of that answer over bruchowski's answer is that it breaks on word boundaries; assuming you care about that sort of thing.
  • Lucas Bernardo de Sousa
    Lucas Bernardo de Sousa about 9 years
    "hellip" - took me sometime to understand we were not talking about satan's ip adress
  • milkovsky
    milkovsky about 9 years
    Update 3 is the most helpful.
  • Alan
    Alan over 8 years
    The top (right now) answer (stackoverflow.com/a/3161830/236306) did nothing (as if I had not used the fn at all). Don't know why. This answer however seems perfect and came with the added benefit of working.
  • crenshaw-dev
    crenshaw-dev about 7 years
    In case there is a hard cap on the length of the returned string, shouldn't line 5 of update 3 be $string = wordwrap($string, $length - sizeof($append)); ?
  • Chaya Cooper
    Chaya Cooper about 7 years
    You're absolutely right, and I edited the answer accordingly. (Revised answer currently awaiting SO peer review)
  • Matt K
    Matt K over 6 years
    Side note if you're using Laravel it has a wrapper function str_limit() that is similar to this answer: return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')).$end
  • MarcoZen
    MarcoZen almost 6 years
    From @Brendon Bullen above .. $string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string; Nice !
  • nickpapoutsis
    nickpapoutsis about 4 years
    WARNING: mb_strimwidth() requires the Multibyte String extension to be installed and activated and that's not always the case so test before deploying.
  • Timo Huovinen
    Timo Huovinen over 3 years
    is this multibyte safe?
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.