views:

54

answers:

3

i wanna get some field values from database and present them on html.

but some of them are longer than the div width so i wanted to chop if of and add 3 dots after them if they are longer than lets say 30 characthers.

windows vs mac os x-> windows vs m...
threads about windows vista -> threads about win...

how can i do that?

A: 

Check out wordwrap(), that should be what you're looking for.

Xorlev
+1  A: 

Judging by your examples you don't seem to care about preserving words, so here it is:

if (strlen($str) > 30)
{
    echo substr($str, 0, 30) . '...';
}
Alix Axel
+5  A: 

If you need to perform this kind of functionality more than once, consider this function:

function truncate($string, $limit, $break = '.', $pad = '...')
{
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit) return $string;

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit)))
    {
        if($breakpoint < strlen($string) - 1)
        {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }

    return $string;
}

Usage:

echo truncate($string, 30);
Dominic Barnes