ajsie
ajsie

Reputation: 79826

how to chop of a text in a certain length with php?

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?

Upvotes: 3

Views: 420

Answers (4)

Maxime Pacary
Maxime Pacary

Reputation: 23081

If you use Smarty, you can use the truncate modifier.

{myLongText|truncate:30:'...':true}

BTW, such kind of function should exist in any decent template engine.

Upvotes: 0

Alix Axel
Alix Axel

Reputation: 154671

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) . '...';
}

Upvotes: 1

Dominic Barnes
Dominic Barnes

Reputation: 28439

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

Upvotes: 6

Xorlev
Xorlev

Reputation: 8653

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

Upvotes: -2

Related Questions