Web Development

Web Development Tips & Tricks, the things that you don’t want to figure out.





Curb a String – PHP Function

I recently had several uses for this function, and there are probably many out. I am not proclaiming this unique nor the best available, but it works which is what counts. I actually took the majority of it from someone else, I think from php.net, but I tweaked it a little bit.

curb function

function curb($text, $maxlen = ”)
{
$MAXLENGTH = (empty($maxlen)) ? 100 : $maxlen; $split = explode(” “, $text);
$numwords = count($split);
$i= 0; //while counter
$a = 1; //counts the text chunks$amount = ceil(strlen($text)/($MAXLENGTH – 5)); //get total word chunks
while($i < $numwords) {
$len = (strlen($newtext[$a]) + strlen($split[$i])); //get length of the active chunk
if($len > ($MAXLENGTH – 5)) { //do we have to start a new one?
$a++;
$newtext[$a] = “[$a/$amount] “; //Adds [1/2]
} else {
$newtext[$a] = $newtext[$a] . ” ” . $split[$i];
$i++;
}
}
return $newtext[1] . “…”; // Don’t want the other variables
}

Pass in the string, and optionally, the length you want to curb it to. You can set a default in the highlighted section of the code (currently set at 100). Right now it returns it with a “…” at the end, which is what I wanted. Go ahead and remove the second highlighted section of the code if you don’t want this. (The highlights are very small – look hard! Squint if you must.)-Kerry

Share and Enjoy:
  • email
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Technorati
  • Google Bookmarks
  • Furl
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...


Leave a reply