Sectionalize Text





9
Date Submitted Thu. Nov. 16th, 2006 5:30 AM
Revision 1 of 1
Beginner Celebhir
Tags characters | PHP | split | String
Comments 0 comments
Function that splits a given string into sections based on the allowed length for a section. Does not split words up. Splits string on Space character (can be set to another character)

/*
 * breaks $text into sections with maximum length no bigger than $allowedlength
 * and not allowing the number of sections returned to be bigger than $maxsections
 * if supplied
 *
 * Earendur Ancalimon
 * 16-11-2006
 */

function sectionalizeLongText($text, $allowedlength, $maxsections = 0)
{
        $splitchar = " ";
        $newcomment = array();
       
        // split $text into array of single 'words'
        $text = split($splitchar, $text);
       
        // set section counter
        $c = 0;
        for( $i = 0; $i < count($text); $i++ )
        {
                // temp store current section and new word
                $temp = $newcomment[$c] . $text[$i] . " ";
               
                // check if new word would make section longer than allowed length
                if( strlen($temp) > $allowedlength )
                {
                        // increment counter (next section)
                        $c++;
                       
                        if( $maxsections > 0 && $c >= $maxsections )
                        {
                                $newcomment[$c-1] = substr($newcomment[$c-1], 0, $allowedlength - 3);
                                $newcomment[$c-1] .= "...";
                                return $newcomment;
                        }
                       
                        if( $i < count($text) )
                        {
                                // initialize
                                $newcomment[$c] = "";
                        }                     
                }
               
                // add on the next word
                $newcomment[$c] .= $text[$i] . " ";
        }
       
        return $newcomment;
}
 

Earendur Ancalimon

Comments

There are currently no comments for this snippet.

Voting