Page 124 - Beginning PHP 5.3
P. 124
Part II: Learning the Language
❑ $numLines : Contains the number of lines of text, computed by counting the number of newline
characters in the text with the substr_count() function
❑ $startOfLine : Points to the index position within $myText of the start of the current line
being processed
Now that the script has initialized these variables, the text can be processed. To do this, the script sets up
a for loop that moves through each line of the text:
for ( $i=0; $i < $numLines; $i++ ) {
Within the loop, the script first computes the length of the original, unjustified line. It does this by
using strpos() to find the index position of the next newline character after the start of the current
line, then subtracting this index position from that of the start of the line:
$originalLineLength = strpos( $myText, “\n”, $startOfLine ) - $startOfLine;
Now that the script knows the length of the line, it ’ s easy to copy the entire line to a new variable,
$justifiedLine , that will hold the justified version of the line. Another variable,
$justifiedLineLength , is set up to track the length of the justified line:
$justifiedLine = substr( $myText, $startOfLine, $originalLineLength );
$justifiedLineLength = $originalLineLength;
The next block of code makes up the meat of the justification algorithm. The script uses a while loop
to run the algorithm repeatedly until the line has been padded out to match the desired line length.
Note that the while loop condition also skips the last line of text, because you don ’ t want this to be
justified:
while ( $i < $numLines - 1 & & $justifiedLineLength < $lineLength ) {
Within the while loop, a for loop works its way through $justifiedLine , character by character. If
the current character is a space, and the line length is still less than the desired length, the script uses
substr_replace() to insert an extra space character at that point. It then increments
$justifiedLineLength to keep track of the current length, and also increments the loop counter, $j ,
to skip over the extra space that ’ s just been created:
for ( $j=0; $j < $justifiedLineLength; $j++ ) {
if ( $justifiedLineLength < $lineLength & & $justifiedLine[$j] == “ “ ) {
$justifiedLine = substr_replace( $justifiedLine, “ “, $j, 0 );
$justifiedLineLength++;
$j++;
}
}
}
The net result of these two loops is that the script moves through the current line from left to right,
adding extra space between each word, until the desired line length is reached. If the desired length isn ’ t
reached by the time the end of the line ’ s reached, the algorithm starts again from left to right, adding
additional spaces. This way the words are spaced as evenly as possible to produce a smooth justification.
86
9/21/09 8:53:44 AM
c05.indd 86
c05.indd 86 9/21/09 8:53:44 AM