Mega Code Archive

 
Categories / Php / Strings
 

A very useful function to display text on specified number of characters

A very easy and useful function to display text on specified number of characters on the fly. This function cut the text on the basis of word boundary. Here is the function <? function cuttext($text, $maxChars = 20, $tail = "") { $arrWords = explode(" ", $text); $temp = ""; for ($i=0; $i<count($arrWords); $i++){ $temp .= ($i == 0 ? $arrWords[$i] : " " . $arrWords[$i]); if (strlen($temp) < $maxChars){ $returnStr = $temp; } else { if (strlen($text) > $maxChars) return $returnStr.$tail; else return $returnStr; } } return $returnStr; } ************** EXAMPLE **************** $string = "A quick brown fox jumps over the lazy dog."; echo cuttext($string, 30, "..."); ************** OUT PUT **************** ?> A quick brown fox jumps over...