CODE: Function to cut text back to certain length
News Headline
Beginning portion of the full news story... Read More
As in the example quote above, this code will accept a text string and a "cutoff" length (minimum of 5) to which it will trim the original string to fit the cutoff length, but except in two circumstances break it off at a space.
The two exceptions are if there is no space before the cutoff value or if the word that it cuts off at is so large, it causes the returned value to be less than half the desired length. (this usually only gets triggered on smaller cutoff values)
I wrote this function tonight after coming across the wordwrap function in php, and decided to rewrite some older code I had to handle this. That code basically used the explode() function to split the string up by spaces, and then loop through adding on pieces until it "fit". Then after being happy at making faster code using the wordwrap mehod, this much simpler method popped in my head!
I did some speed tests on my old and fairly optimized code against the method using the word wrap, and this one was about 3-4 times faster than my original, and still slightly faster than the wordwrap method.
Enjoy the code, let me know if you have any questions or improvements on it.
-Greg
function ChopWords($text,$cutoff=5) {
if ($cutoff<5) $cutoff=5;
if (strlen($text)>$cutoff) {
$text = substr($text,0,$cutoff-2);
$pos = strrpos($text," ");
if ($pos===false || ($pos+3<=$cutoff/2))
$text = substr($text,0,-1);
else {
$text = substr($text,0,$pos);
}
$text .= '...';
}
return $text;
}
demonhale posted this at 07:50 — 15th August 2008.
He has: 3,278 posts
Joined: May 2005
Nice Greg, I'll keep this in mind when coding my next project, this could prove really useful...
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.