wrathican Posted August 7, 2007 Share Posted August 7, 2007 what i want to do is trim a value that is pulled from the DB down to 100 chars or maybe a maximum number of words. how would i do this? Quote Link to comment https://forums.phpfreaks.com/topic/63712-solved-trim-a-string-from-db/ Share on other sites More sharing options...
Daniel0 Posted August 7, 2007 Share Posted August 7, 2007 <?php $string = "This is a test of the truncate function"; function truncate($string, $max_length) { if(strlen($string) > $max_length-3) { $string = substr($string, 0, $max_length-3).'...'; } return $string; } echo truncate($string, 15); // This is a te... function truncate2($string, $max_words) { $str = null; if(str_word_count($string) > $max_words) { preg_match('/^\s*(?:\S+\s*){1,'. (int) $max_words .'}/', $string, $matches); $str = trim($matches[0]).'...'; } else { $str = $string; } return $str; } echo truncate2($string, 4); // This is a test... ?> Quote Link to comment https://forums.phpfreaks.com/topic/63712-solved-trim-a-string-from-db/#findComment-317486 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.