ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

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($strTemp16"..."); 
print 
$strTemp;
?> 

Leave a Reply