note 103671 deleted from function.wordwrap by danbrown

From: Date: Wed, 27 Apr 2011 15:12:07 +0000
Subject: note 103671 deleted from function.wordwrap by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179197@lists.php.net to get a copy of this message
Note Submitter: havelangep at hotmail dot com ---- An updated version of the justify function writen by thomas at toghome dot com. This version should work on PHP5 (fixed issues with array index type and multibyte sequences) <?php // Usage: // // echo stringTools::justify( $str, 80 ) . "\n"; // class stringTools { const PAD_LEFT = 1; // More spaces are added on the left of the line const PAD_RIGHT = 2; // More spaces are added on the right of the line const PAD_BOTH = 4; // Tries to evenly distribute the padding const PAD_AVERAGE = 8; // Tries to position based on a mix of the three algorithms /** * @param string $input * @param int $width * @param int $mode * @return string * @author MetaNull */ function justify($input, $width, $mode = self::PAD_BOTH){ $final = ''; // We want to have n characters wide of text per line. // Use PHP's wordwrap feature to give us a rough estimate. $justified = self::wordwrap($input, $width, "\n", false); $justified = explode("\n", $justified); // Check each line is the required width. If not, pad it with spaces between words. foreach($justified as $line){ if(strlen($line) != $width){ // Split by word, then glue together $words = preg_split('/ /', $line); $diff = $width - mb_strlen($line); while($diff > 0) { // Process the word at this diff $wordsIndex = null; if($mode == self::PAD_BOTH) { $wordsIndex = (int)($diff / count($words)); } else if($mode == self::PAD_AVERAGE) { $wordsIndex = (int)((($diff / count($words)) + ($diff % count($words)) + (count($words) - ($diff % count($words)))) / 3); } else if($mode == self::PAD_LEFT) { $wordsIndex = (int)($diff % count($words)); } else if($mode == self::PAD_RIGHT) { $wordsIndex = (int)(count($words) - ($diff % count($words))); } if( null !== $wordsIndex ) { if( !array_key_exists($wordsIndex, $words )) { $words[$wordsIndex] = ''; } $words[$wordsIndex] .= ' '; } // Next diff, please... $diff--; } } else { $words = preg_split('/ /', $line); } $final .= implode(' ', $words) . "\n"; } // Return the final string return $final; } public static function wordwrap( $string, $width, $break ) { return wordwrap($string,$width,$break); } } ?>

« previous php.notes (#179197) next »