adamlacombe Posted July 9, 2010 Share Posted July 9, 2010 I want it so if $str has too many characters to limit it, I dont want it to cut off in the middle of a word, and I want "..." at the end of the $str if there is more to it that is hidden. so I came up with this: function browsedesclimit($str) { if (strlen($str) < 30){ $str = substr($str, 0, 30); $words = explode(' ', preg_replace("/\s+/", ' ', preg_replace("/(\r\n|\r|\n)/", " ", $str))); if (count($words) <= 10){ for ($i = 0; $i < 30; $i++){ $str .= $words[$i].' '; } } return trim($str).'...'; }else{ return $str; } } I am not the best with functions so any help at all would be great, thanks! Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 9, 2010 Share Posted July 9, 2010 Here's my function which seems to be more efficient and flexible. Just pass the string and the max characters to allow. It will reduce it to the first space character before the max limit and add ellipses if needed. The third parameter is optional for setting a custom string for the ellipses function truncateString($string, $length, $ellipse='...') { if (strlen($string) <= $length) { return $string; } return array_shift(explode("\n", wordwrap($string, $length))) . $ellipse; } $text = "This is a long string with many, many words and it should be truncated"; echo truncateString($text, 45); //Output: "This is a long string with many, many words..." You should probably trim() the string beforehand. Quote Link to comment Share on other sites More sharing options...
adamlacombe Posted July 9, 2010 Author Share Posted July 9, 2010 ok, great! Thanks very much! just what I needed Quote Link to comment 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.