[PHP] Crop text
6 April 2011
No Comment
The function crop_text() crops certain string by word count.
so If you have a string like this:
$text = “The quick brown fox jumps over the lazy dog”;
running crop_text($text,5,’…’) will return:
“The quick brown fox jumps…”
Here is the function
<?
function crop_text($text,$len,$sep){
$cropped = '';
$words = explode(' ', $text);
//split the paragraph into array of words
if(count($words) < $len){
$cropped = $text;
//if the word count is less than the desired length accept it all
}else{
for($i=0;$i<$len;$i++){
$cropped .= ' '.$words[$i];
//concatinating the words into one string
}
$cropped = $cropped.$sep;
//append the ending text e.g. ('...' or read more etc)
}
return $cropped;
}
?>
Your opinion matters!