tags:

views:

322

answers:

7

What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?

+7  A: 
//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 '...'

Brendan Bullen
However, you'd need to check if you actually docked the string, as you wouldn't want to add '...' to $string="Hello"; since it is less than 10 characters.
MarkD
good point! A simple ternary conditional should do it
Brendan Bullen
This is what the OP asked for, and what every implementation looks like, but I'd recommend checking `strlen($string) > 13)` instead; there's no reason to truncate the last three characters of the string if you're going to replace it with '...'
Michael Mrozek
+1  A: 
if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";
HCL
+2  A: 

Use substring

http://php.net/manual/en/function.substr.php

$foo = substr("abcde",0, 3) . "...";
Ziplin
This code will always add ... to the string, which he didn't want.
TravisO
A: 

It's best to abstract you're code like so (notice the limit is optional and defaults to 10):

print Limit($string);


function Limit($var, $limit=10)
{
    if ( strlen($var) > $limit )
    {
        return substr($string, 0, $limit) . '...';
    }
    else
    {
        return $var;
    }
}
TravisO
That won't work because [trim()](http://de3.php.net/manual/en/function.trim.php) already exists.
Gordon
Could explain why this approach is best instead of just asserting that it is?
Robert
@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
+1  A: 

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, $charset) . '...';
}
Emil Vikström
A: 

substr() would be best, you'll also want to check the length of the string first

$str = 'someLongString';
$max = 7;

if(strlen($str) > $max) {
   $str = substr($str, 0, $max) . '...';
}

wordwrap won't trim the string down, just split it up...

tsgrasser
A: 

The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html (just read the word_limiter and character_limiter sections). Here's two functions from it relevant to your question:

if ( ! function_exists('word_limiter'))
{
    function word_limiter($str, $limit = 100, $end_char = '…')
    {
        if (trim($str) == '')
        {
            return $str;
        }

        preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);

        if (strlen($str) == strlen($matches[0]))
        {
            $end_char = '';
        }

        return rtrim($matches[0]).$end_char;
    }
}

And

if ( ! function_exists('character_limiter'))
{
    function character_limiter($str, $n = 500, $end_char = '…')
    {
        if (strlen($str) < $n)
        {
            return $str;
        }

        $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));

        if (strlen($str) <= $n)
        {
            return $str;
        }

        $out = "";
        foreach (explode(' ', trim($str)) as $val)
        {
            $out .= $val.' ';

            if (strlen($out) >= $n)
            {
                $out = trim($out);
                return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
            }       
        }
    }
}
Matthew