Crop sentence
Use this handy function, written by David Speake, to crop a sentence to a certain length. This function makes sure the words don’t get broken up in the middle.
/*################################################################
# #
# You pass the script a string, a length you want the string #
# to be and the trailing characters, what the function does, #
# is takes the string, finds the last word that will fit into #
# the overall length, and return a string that has been cropped. #
# The function makes sure that a word is not cut in half. #
# #
##################################################################
# Written by David Speake - [email protected] #
# Adapted from Oliver Southgate's ASP interpretation #
# http://www.haneng.com/code/VBScript/CropSentence.txt #
##################################################################
# #
# Examples: #
# #
# $strTemp = "Hello, I am a fish and you are not."; #
# $strTemp = CropSentence($strTemp, 16, "..."); #
# //returns "Hello, I am a..." #
# #
# $strTemp = "Hello, I am a fish and you are not."; #
# $strTemp = CropSentence($strTemp, 17, "..."); #
# //returns "Hello, I am a fish..." #
# #
################################################################*/
function CropSentence ($strText, $intLength, $strTrail)
{
$wsCount = 0;
$intTempSize = 0;
$intTotalLen = 0;
$intLength = $intLength - strlen($strTrail);
$strTemp = "";
if (strlen($strText) > $intLength) {
$arrTemp = explode(" ", $strText);
foreach ($arrTemp as $x) {
if (strlen($strTemp) <= $intLength) $strTemp .= " " . $x;
}
$CropSentence = $strTemp . $strTrail;
} else {
$CropSentence = $strText;
}
return $CropSentence;
}
$strTemp = "Hello, I am a fish and you are not.";
$strTemp = CropSentence($strTemp, 16, "...");
print $strTemp;
?>