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? 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... ?> 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
Archived
This topic is now archived and is closed to further replies.