string manipulation question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Milan
Forum Commoner
Posts: 97
Joined: Wed May 17, 2006 6:08 pm

string manipulation question

Post by Milan »

Woa! My third question today and i do know i am getting borring :P

but PHP is so much fun!

I would like to know how to trim the variable to display only the first 200 characters of description? :roll:

thanks a lot guys!
litebearer
Forum Contributor
Posts: 194
Joined: Sat Mar 27, 2004 5:54 am

Post by litebearer »

This will truncate a string to a chosen length, make sure it does NOT chop off in the middle of a word, and add trailing dots.

Code: Select all

<?PHP

function truncate_string($details,$max)
{
    if(strlen($details)>$max)
    {
        $details = substr($details,0,$max);
        $i = strrpos($details," ");
        $details = substr($details,0,$i);
        $details = $details." ..... ";
    }
    return $details;
}

$text = truncate_string("hello there. This is a long string",19);

?>
Lite...
Milan
Forum Commoner
Posts: 97
Joined: Wed May 17, 2006 6:08 pm

thanks!

Post by Milan »

Thanks a lot!
Post Reply