note 58771 deleted from function.str-pad by danbrown

From: Date: Sat, 02 Jul 2011 18:55:55 +0000
Subject: note 58771 deleted from function.str-pad by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181192@lists.php.net to get a copy of this message
Note Submitter: Silvio Ginter (silvio dot ginter at gmx dot de) ---- Hello, for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments. <?php $string = 'this is a test'; $oldLen = strlen($string); $direction = STR_PAD_BOTH; echo $string.'<br>'; echo str_const_len($string, 100, '#', $direction).'<br>'; echo $string.'<br>'; echo str_const_len($string, $oldLen, '#', $direction).'<br>'; echo $string.'<br><br>'."\n"; /* This function is an extension to str_pad. It manipulates the referenced string '$str' and stretches or reduces it to the specified length. It returns the number of characters, that were added or stripped. */ function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) { $dir = STR_PAD_RIGHT; $origLen = strlen($str); if (strlen($str) < $len) { /* stretch string */ $str = str_pad($str, $len, $char, $str_pad_const); } else { /* reduce string */ switch ($str_pad_const) { case STR_PAD_LEFT: $str = substr($str, (strlen($str) - $len), $len); break; case STR_PAD_BOTH: /* reduce on both sides, beginning with the right one. */ while (strlen($str) > $len) { if ($dir == STR_PAD_RIGHT) { $str = substr($str, 0, (strlen($str) - 1)); $dir = STR_PAD_LEFT; } else { $str = substr($str, 1); $dir = STR_PAD_RIGHT; } } break; default: $str = substr($str, 0, $len); break; } } return ($len - $origLen); } ?>

« previous php.notes (#181192) next »